一、前言
通过AES加密算法实现密码加密工具类PasswordEncodeUtils,这边通过javax.crypto.Cipher获取AES加密解密实例,下面通过具体示例代码进行说明。
二、代码示例
package test;@b@@b@@b@import java.io.BufferedReader;@b@import java.io.InputStreamReader;@b@import java.math.BigInteger;@b@import java.security.InvalidKeyException;@b@import java.security.NoSuchAlgorithmException;@b@@b@import javax.crypto.BadPaddingException;@b@import javax.crypto.Cipher;@b@import javax.crypto.IllegalBlockSizeException;@b@import javax.crypto.NoSuchPaddingException;@b@import javax.crypto.spec.SecretKeySpec;@b@@b@public class PasswordEncodeUtils {@b@@b@ private static byte[] ENC_KEY_BYTES = "This is a finger".getBytes();@b@@b@ private static String encode(String encKey, String secret)@b@ throws NoSuchAlgorithmException, NoSuchPaddingException,@b@ InvalidKeyException, IllegalBlockSizeException, BadPaddingException {@b@ byte[] kbytes = ENC_KEY_BYTES;@b@ if (encKey != null && !"".equals(encKey))@b@ kbytes = encKey.getBytes();@b@@b@ SecretKeySpec key = new SecretKeySpec(kbytes, "AES");@b@ Cipher cipher = Cipher.getInstance("AES");@b@ cipher.init(1, key);@b@ byte[] encoding = cipher.doFinal(secret.getBytes());@b@ BigInteger n = new BigInteger(encoding);@b@ return n.toString(16);@b@ }@b@@b@ public static String encode(String secret) throws NoSuchPaddingException,@b@ NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,@b@ IllegalBlockSizeException {@b@ return encode(null, secret);@b@ }@b@@b@ private static String decode(String encKey, String secret)@b@ throws NoSuchPaddingException, NoSuchAlgorithmException,@b@ InvalidKeyException, BadPaddingException, IllegalBlockSizeException {@b@ byte[] kbytes = ENC_KEY_BYTES;@b@ if (encKey != null && !"".equals(encKey))@b@ kbytes = encKey.getBytes();@b@@b@ SecretKeySpec key = new SecretKeySpec(kbytes, "AES");@b@ BigInteger n = new BigInteger(secret, 16);@b@ byte[] encoding = n.toByteArray();@b@ Cipher cipher = Cipher.getInstance("AES");@b@ cipher.init(2, key);@b@ byte[] decode = cipher.doFinal(encoding);@b@ return new String(decode);@b@ }@b@@b@ public static String decode(String secret) throws NoSuchPaddingException,@b@ NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,@b@ IllegalBlockSizeException {@b@ return decode(null, secret);@b@ }@b@@b@ public static void main(String[] args) throws Exception {@b@ BufferedReader br=new BufferedReader(new InputStreamReader(System.in));@b@ System.out.println("请输入您的账号密码并回车:");@b@ String pwd=br.readLine();@b@ String encPasswd = PasswordEncodeUtils.encode(pwd);@b@ System.out.println("原密码:" + pwd);@b@ System.out.println("加密后的密码:" + encPasswd);@b@ @b@ }@b@}
控制台结果
请输入您的账号密码并回车:@b@xwood123@b@原密码:xwood123@b@加密后的密码:-28f4e37f1a9bcb21244c1d261062d721