项目中也经常使用加密方式,Base64加密,AES加密,下面记录下使用AES加密方式
package com.czb; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Encoder; public class Test { public static void main(String[] args) throws Exception{ //AES加密方式 String secKey = "afaaGn_A2bytbd10";//密钥 BASE64Encoder encoder = new sun.misc.BASE64Encoder(); SecretKey sKey = new SecretKeySpec(secKey.getBytes(), "AES"); Cipher ci = Cipher.getInstance("AES"); ci.init(Cipher.ENCRYPT_MODE, sKey); byte[] b = ci.doFinal("呵呵".getBytes()); System.out.println(encoder.encode(b)); } }
解密
BASE64Decoder decoder = new BASE64Decoder(); byte[] content = decoder.decodeBuffer(encoder.encode(b)); byte[] enCodeFormat = "afaaGn_A2bytbd10".getBytes(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(content); System.out.println( new String(result));
时间: 2024-10-10 07:31:00