//欲加密的字串 String msg = "This is a message."; System.out.println("原始字串:"+new String(msg)); //设定要使用的加密演算法 KeyGenerator keyG = KeyGenerator.getInstance("AES"); //设定key的长度 keyG.init(256); //产生SecretKey SecretKey secuK = keyG.generateKey(); //取得要用来加密的key(解密也需使用这把key) byte[] key = secuK.getEncoded(); System.out.println("key:"+new String(key)); SecretKeySpec spec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); //设定为加密模式 cipher.init(Cipher.ENCRYPT_MODE, spec); //将字串加密,并取得加密后的资料 byte[] encryptData = cipher.doFinal(msg.getBytes()); System.out.println("加密后字串:"+new String(encryptData)); //使用刚刚用来加密的key进行解密 spec = new SecretKeySpec(key, "AES"); cipher = Cipher.getInstance("AES"); //设定为解密模式 cipher.init(Cipher.DECRYPT_MODE, spec); byte[] original = cipher.doFinal(encryptData); System.out.println("解密后字串:"+new String(original));
输出结果
原始字串:This is a message.
key:�U{� jPk ���@7 .�A@��&]W LK���ݣ
加密后字串:��� � ����tl7Q U!���d�{4R) �� .
解密后字串:This is a message.
key:�U{� jPk ���@7 .�A@��&]W LK���ݣ
加密后字串:��� � ����tl7Q U!���d�{4R) �� .
解密后字串:This is a message.
沒有留言:
張貼留言