一、工具类说明
这边基于javax.crypto.Cipher获取AES数据加密实例,并通过javax.crypto.spec.SecretKeySpec对安全密钥进行加解密处理,下面给出了一个默认密钥和自定义密钥的对密码常用加解密处理工具类代码,具体如下
import java.math.BigInteger;@b@import javax.crypto.Cipher;@b@import javax.crypto.SecretKey;@b@import javax.crypto.spec.SecretKeySpec;@b@@b@public class PasswordCodeUtils {@b@@b@ private static byte[] ENC_KEY_BYTES = "Q0L4GOr4a01u6GQ4".getBytes();@b@ @b@ private static SecretKeySpec DEF_KEY = new SecretKeySpec(ENC_KEY_BYTES, "AES");@b@ @b@ @b@ public static String encode(SecretKey key, String datas) throws Exception {@b@ Cipher cipher = Cipher.getInstance("AES");@b@ cipher.init(1, key);@b@ byte[] encoding = cipher.doFinal(datas.getBytes());@b@ BigInteger n = new BigInteger(encoding);@b@ return n.toString(16);@b@ }@b@@b@ public static String encode(String datas){@b@ try {@b@ return encode(DEF_KEY, datas);@b@ } catch (Exception e) {@b@ throw new RuntimeException("PasswordEncode error,cause:"+e.getMessage(),e);@b@ }@b@ }@b@@b@ public static String decode(SecretKey key, String datas) throws Exception {@b@ BigInteger n = new BigInteger(datas, 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 datas) {@b@ try {@b@ return decode(DEF_KEY, datas);@b@ } catch (Exception e) {@b@ throw new RuntimeException("PasswordDecode error,cause:"+e.getMessage(),e);@b@ }@b@ }@b@@b@ public static void main(String[] args) throws Exception {@b@ String password = "test1234$";@b@ String encPasswd = PasswordCodeUtils.encode(password);@b@ System.out.println("原密码:" + password);@b@ System.out.println("加密后的密码:" + encPasswd);@b@ System.out.println("解密后的密码:" + PasswordCodeUtils.decode(encPasswd));@b@ }@b@}
运行后,结果如下
原密码:test1234$@b@加密后的密码:-375da61eebac5c536d70ffdb3d3e0722@b@解密后的密码:test1234$