美文网首页
java对称加解密

java对称加解密

作者: simplerandom | 来源:发表于2020-06-19 15:27 被阅读0次
    public class Test {
        public static void main(String[] args) throws Exception {
            // 加密信息"Hello, world!",加密key数组1234567890abcdef,16个字节
            String message = "Hello, world!";
            System.out.println("Message: " + message);
            // 128位密钥 = 16 bytes Key:
            byte[] key = "1234567890abcdef".getBytes("UTF-8");
            // 加密:
            byte[] data = message.getBytes("UTF-8");
            byte[] encrypted = encrypt(key, data);
            System.out.println("Encrypted: " + Base64.getEncoder().encodeToString(encrypted));
            // 解密:
            byte[] decrypted = decrypt(key, encrypted);
            System.out.println("Decrypted: " + new String(decrypted, "UTF-8"));
        }
    
        // 加密:
        public static byte[] encrypt(byte[] key, byte[] input) throws GeneralSecurityException {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKey keySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            return cipher.doFinal(input);
        }
    
        // 解密:
        public static byte[] decrypt(byte[] key, byte[] input) throws GeneralSecurityException {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKey keySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            return cipher.doFinal(input);
        }
    }
    

    相关文章

      网友评论

          本文标题:java对称加解密

          本文链接:https://www.haomeiwen.com/subject/khovxktx.html