JAVA实现AES加密算法代码
AES加密解密代码(key是16位)--java

AES加密解密代码(key是16位)--java import javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;import mons.codec.binary.Base64;public class AES16 {// 加密public static String Encrypt(String sSrc, String sKey) throws Exception {if (sKey == null) {System.out.print("Key为空null");return null;}// 判断Key是否为16位if (sKey.length() != 16) {System.out.print("Key长度不是16位");return null;}byte[] raw = sKey.getBytes("utf-8");SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码⽅式"cipher.init(Cipher.ENCRYPT_MODE, skeySpec);byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));return new Base64().encodeToString(encrypted);//此处使⽤BASE64做转码功能,同时能起到2次加密的作⽤。
}// 解密public static String Decrypt(String sSrc, String sKey) throws Exception {try {// 判断Key是否正确if (sKey == null) {System.out.print("Key为空null");return null;}// 判断Key是否为16位if (sKey.length() != 16) {System.out.print("Key长度不是16位");return null;}byte[] raw = sKey.getBytes("utf-8");SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");cipher.init(Cipher.DECRYPT_MODE, skeySpec);byte[] encrypted1 = new Base64().decode(sSrc);//先⽤base64解密try {byte[] original = cipher.doFinal(encrypted1);String originalString = new String(original,"utf-8");return originalString;} catch (Exception e) {System.out.println(e.toString());return null;}} catch (Exception ex) {System.out.println(ex.toString());return null;}}/**** @Description AES解密,加密内容转化为16位⼆进制后解密mxg20190906* @return String* @author mxg*/public static String aesDecrypt(String sSrc, String sKey) throws Exception {try {// 判断Key是否正确if (sKey == null) {System.out.print("Key为空null");return null;}// 判断Key是否为16位if (sKey.length() != 16) {System.out.print("Key长度不是16位");return null;}byte[] raw = sKey.getBytes("utf-8");SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec);// byte[] encrypted1 = new Base64().decode(sSrc);//先⽤base64解密try {byte[] original = cipher.doFinal( parseHexStr2Byte(sSrc));String originalString = new String(original,"utf-8");return originalString;} catch (Exception e) {System.out.println(e.toString());return null;}} catch (Exception ex) {System.out.println(ex.toString());return null;}}/**将16进制转换为⼆进制* @param hexStr* @return*/public static byte[] parseHexStr2Byte(String hexStr) {if (hexStr.length() < 1)return null;byte[] result = new byte[hexStr.length()/2];for (int i = 0;i< hexStr.length()/2; i++) {int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);result[i] = (byte) (high * 16 + low);}return result;}public static void main(String[] args) throws Exception {/** 此处使⽤AES-128-ECB加密模式,key需要为16位。
aes-gcm用法

aes-gcm用法AES-GCM(Advanced Encryption Standard - Galois/Counter Mode)是一种对称加密算法,常用于数据的加密和认证。
以下是AES-GCM的用法示例:1. 密钥生成:生成一个16字节(128位)的密钥。
可以使用安全的随机数生成器来生成密钥。
```javaSecureRandom secureRandom = new SecureRandom();byte[] key = new byte[16];secureRandom.nextBytes(key);```2. 加密:使用密钥对数据进行加密。
```javabyte[] plaintext = "Hello, World!".getBytes();byte[] iv = new byte[12]; // 初始化向量,长度为12字节secureRandom.nextBytes(iv);Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, iv);cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);byte[] ciphertext = cipher.doFinal(plaintext);```3. 解密:使用密钥对加密后的数据进行解密。
```javacipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);byte[] decryptedText = cipher.doFinal(ciphertext);```注意:在实际使用中,需要考虑更多的安全性和错误处理措施,上述示例只是简单的用法演示。
Java使用Cipher类实现加密,包括DES,DES3,AES和RSA加密

Java使⽤Cipher类实现加密,包括DES,DES3,AES和RSA加密⼀、先看⼀个简单加密,解密实现1.1 加密/*** content: 加密内容* slatKey: 加密的盐,16位字符串* vectorKey: 加密的向量,16位字符串*/public String encrypt(String content, String slatKey, String vectorKey) throws Exception {Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), "AES");IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);byte[] encrypted = cipher.doFinal(content.getBytes());return Base64.encodeBase64String(encrypted);}1.2 解密/*** content: 解密内容(base64编码格式)* slatKey: 加密时使⽤的盐,16位字符串* vectorKey: 加密时使⽤的向量,16位字符串*/public String decrypt(String base64Content, String slatKey, String vectorKey) throws Exception {Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), "AES");IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);byte[] content = Base64.decodeBase64(base64Content);byte[] encrypted = cipher.doFinal(content);return new String(encrypted);}1.3 代码解释上⾯简单实现了AES("AES/CBC/PKCS5Padding")的加密和解密。
JAVA实现AES加密算法代码

JAVA实现AES加密算法代码以下是一个简单的JAVA实现AES加密算法的代码:```javaimport javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;import java.security.Key;public class AESprivate static final String ALGORITHM = "AES";private static final String TRANSFORMATION ="AES/ECB/PKCS5Padding";public static byte[] encrypt(String key, byte[] data) throws ExceptionKey secretKey = new SecretKeySpec(key.getBytes(, ALGORITHM);Cipher cipher = Cipher.getInstance(TRANSFORMATION);cipher.init(Cipher.ENCRYPT_MODE, secretKey);return cipher.doFinal(data);}public static byte[] decrypt(String key, byte[] encryptedData) throws ExceptionKey secretKey = new SecretKeySpec(key.getBytes(, ALGORITHM);Cipher cipher = Cipher.getInstance(TRANSFORMATION);cipher.init(Cipher.DECRYPT_MODE, secretKey);return cipher.doFinal(encryptedData);}public static void main(String[] args)tryString key = "ThisIsASecretKey";String data = "Hello World!";byte[] encryptedData = encrypt(key, data.getBytes();System.out.println("Encrypted Data: " + newString(encryptedData));byte[] decryptedData = decrypt(key, encryptedData);System.out.println("Decrypted Data: " + newString(decryptedData));} catch (Exception e)e.printStackTrace(;}}```这个代码包含了两个方法,一个是用于加密数据的`encrypt`方法,另一个是用于解密数据的`decrypt`方法。
JAVA实现AES的加密和解密算法

JAVA实现AES的加密和解密算法JAVA实现AES的加密和解密算法加密模式为 AES-128-CBC1import javax.crypto.Cipher;2import javax.crypto.spec.IvParameterSpec;3import javax.crypto.spec.SecretKeySpec;45import sun.misc.BASE64Decoder;6import sun.misc.BASE64Encoder;78/**AES 是⼀种可逆加密算法,对⽤户的敏感信息加密处理9* 对原始数据进⾏AES加密后,在进⾏Base64编码转化;10*/11public class AESOperator {12/*13* 加密⽤的Key 可以⽤26个字母和数字组成14* 此处使⽤AES-128-CBC加密模式,key需要为16位。
15*/16private String sKey=”0123456789abcdef”;17private String ivParameter=”0123456789abcdef”;18private static AESOperator instance=null;19private AESOperator(){2021 }22public static AESOperator getInstance(){23if (instance==null)24 instance= new AESOperator();25return instance;26 }27// 加密28public String encrypt(String sSrc) throws Exception {29 Cipher cipher = Cipher.getInstance(“AES/CBC/PKCS5Padding”);30byte[] raw = sKey.getBytes();31 SecretKeySpec skeySpec = new SecretKeySpec(raw, “AES”);32 IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());//使⽤CBC模式,需要⼀个向量iv,可增加加密算法的强度33 cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);34byte[] encrypted = cipher.doFinal(sSrc.getBytes(“utf-8″));35return new BASE64Encoder().encode(encrypted);//此处使⽤BASE64做转码。
javaAES实现字符串的加密、解密(配合二进制、十六进制转换的工具使用)

javaAES实现字符串的加密、解密(配合⼆进制、⼗六进制转换的⼯具使⽤)//BinHexSwitchUtil 参考这个链接https:///xiaoxiao075/p/13230454.htmlimport javax.crypto.*;import javax.crypto.spec.SecretKeySpec;import java.security.InvalidKeyException;import java.security.Key;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.util.Arrays;import java.util.Base64;//import mons.codec.binary.Base64;public class EncryptStrUtil {/*** KeyGenerator的⽅式,通过传⼊种⼦串⽣成key,进⾏加密* @param seed ⽣成key传⼊的种⼦串* @param toEncryptStr 要加密的字节数组* @return返回 Base64 的加密字符串*/public static String encrypt(String seed, byte[] toEncryptStr) {try {return Base64.getEncoder().encodeToString(getCipher(seed, Cipher.ENCRYPT_MODE).doFinal(toEncryptStr)); //此时使⽤的 Base64 编码} catch (Exception e) {e.printStackTrace();}return null;}/*** 根据传⼊的⼆进制 key数组,返回AES的⼗六进制加密串* @param keyBytes* @param toEncryptStr* @return*/public static String encrypt(byte[] keyBytes, byte[] toEncryptStr) {try {return BinHexSwitchUtil.bytesToHexString(getCipher(keyBytes, Cipher.ENCRYPT_MODE).doFinal(toEncryptStr));} catch (Exception e) {e.printStackTrace();}return null;}/*** KeyGenerator的⽅式,通过传⼊种⼦串⽣成key,进⾏解密* @param seed ⽣成key传⼊的种⼦串* @param encryptedStr 要解密的字节数组,Base64加密的* @return返回解密的字节数组*/public static byte[] decrypt(String seed, byte[] encryptedStr) {try {return getCipher(seed, Cipher.DECRYPT_MODE).doFinal(Base64.getDecoder().decode(encryptedStr));} catch (Exception e) {e.printStackTrace();}return null;}/*** 根据传⼊的⼆进制 key数组,将16进制加密串解密* @param keyBytes* @param encryptedStr 要解密的字符串* @return已解密的⼆进制数组*/public static byte[] decrypt(byte[] keyBytes, String encryptedStr) {try {return getCipher(keyBytes, Cipher.DECRYPT_MODE).doFinal(BinHexSwitchUtil.hexStringTobytes(encryptedStr));} catch (Exception e) {e.printStackTrace();}return null;}/*** KeyGenerator 的⽅式⽣成key,获取密码⽣成器* @param seed 传⼊的种⼦字符串* @param encryptMode 传⼊加密模式、解密模式* @return返回密码⽣成器* @throws Exception*/private static Cipher getCipher(String seed, int encryptMode) throws Exception {//⽣成加密随机数SecureRandom random = SecureRandom.getInstance("SHA1PRNG");//并设置seedrandom.setSeed(seed.getBytes());//创建AES⽣产者KeyGenerator generator = KeyGenerator.getInstance("AES");//初始化⽣产者,128位generator.init(128, random);Key key=generator.generateKey();// 返回基本编码格式的密钥(初始key),如果此密钥不⽀持编码,则返回null。
Java使用AES-256加密

Java使⽤AES-256加密Java version: 1.8.0_151-b12AES(Advanced Encryption Standard)加密算法属于对称加密算法,AES加密算法的安全性要⾼于DES和3DES, 所以AES已经成为了主要的对称加密算法.AES的加密流程要理解AES的加密流程, 会涉及到AES的五个关键词: 分组密码体制, Padding, 初始向量IV, 密钥, 加密模式.分组密码体制: 所谓分组密码体制就是指将明⽂切成⼀段⼀段的来加密, 然后再把⼀段⼀段的密⽂拼起来形成最终密⽂的加密⽅式. AES采⽤分组密码体制, 即AES加密会⾸先把明⽂切成⼀段⼀段的, ⽽且每段数据的长度要求必须是128位16个字节, 如果最后⼀段不够16个字节了, 就需要⽤Padding来把这段数据填满16个字节, 然后分别对每段数据进⾏加密, 最后再把每段加密数据拼起来形成最终的密⽂.Padding: Padding就是⽤来把不满16个字节的分组数据填满16个字节⽤的, 它有三种模式PKCS5、PKCS7和NOPADDING. PKCS5是指分组数据缺少⼏个字节, 就在数据的末尾填充⼏个字节的⼏, ⽐如缺少5个字节, 就在末尾填充5个字节的5. PKCS7是指分组数据缺少⼏个字节, 就在数据的末尾填充⼏个字节的0, ⽐如缺少7个字节, 就在末尾填充7个字节的0. NoPadding是指不需要填充, 也就是说数据的发送⽅肯定会保证最后⼀段数据也正好是16个字节. 那如果在PKCS5模式下, 最后⼀段数据的内容刚好就是16个16怎么办?那解密端就不知道这⼀段数据到底是有效数据还是填充数据了, 因此对于这种情况, PKCS5模式会⾃动帮我们在最后⼀段数据后再添加16个字节的数据, ⽽且填充数据也是16个16, 这样解密段就能知道谁是有效数据谁是填充数据了. PKCS7最后⼀段数据的内容是16个0, 也是同样的道理. 解密端需要使⽤和加密端同样的Padding模式, 才能准确的识别有效数据和填充数据. 我们开发通常采⽤PKCS7 Padding模式.初始向量IV: 初始向量IV的作⽤是使加密更加安全可靠, 我们使⽤AES加密时需要主动提供初始向量, ⽽且只需要提供⼀个初始向量就够了, 后⾯每段数据的加密向量都是前⾯⼀段的密⽂. 初始向量IV的长度规定为128位16个字节, 初始向量的来源为随机⽣成.密钥: AES要求密钥的长度可以是128位16个字节、192位或者256位, 位数越⾼, 加密强度⾃然越⼤, 但是加密的效率⾃然会低⼀些, 因此要做好衡量. 我们开发通常采⽤128位16个字节的密钥, 我们使⽤AES加密时需要主动提供密钥, ⽽且只需要提供⼀个密钥就够了, 每段数据加密使⽤的都是这⼀个密钥, 密钥来源为随机⽣成.加密模式: AES⼀共有四种加密模式, 分别是ECB(电⼦密码本模式)、CBC(密码分组链接模式)、CFB、OFB, 我们⼀般使⽤的是CBC模式. 四种模式中除了ECB相对不安全之外, 其它三种模式的区别并没有那么⼤. ECB模式是最基本的加密模式, 即仅仅使⽤明⽂和密钥来加密数据, 相同的明⽂块会被加密成相同的密⽂块, 这样明⽂和密⽂的结构将是完全⼀样的, 就会更容易被破解, 相对来说不是那么安全, 因此很少使⽤. CBC模式则⽐ECB模式多了⼀个初始向量IV, 加密的时候, 第⼀个明⽂块会⾸先和初始向量IV做异或操作, 然后再经过密钥加密, 然后第⼀个密⽂块⼜会作为第⼆个明⽂块的加密向量来异或, 依次类推下去, 这样相同的明⽂块加密出的密⽂块就是不同的, 明⽂的结构和密⽂的结构也将是不同的, 因此更加安全, 我们常⽤的就是CBC加密模式.说完 AES 加密流程, 下⾯说⼀说 Java 如何使⽤ AES 加密.或许你⼀直使⽤ AES-128 加密没有任何问题, 但当你把密钥增加到32个字节的时候, 可能会遇到如下异常:java.security.InvalidKeyException: Illegal key sizeTo solve that you have to go to , download the Unlimited Strength Jurisdiction Policy Files, unzip it, go to the <java-home>/lib/security directory,and replace the two files local_policy.jar and US_export_policy.jar with the two files from the download.Starting with Java 1.8.0_151 and 1.8.0_152 there is a new somewhat easier way to enable the unlimited strength jurisdiction policy for the JVM. Withoutenabling this you cannot use AES-256. Since this version, it is no longer necessary to download the policy files from the Oracle website and install it. Youcan now set the unlimited policy directly in your application with this one-liner:Security.setProperty("crypto.policy", "unlimited");In Java 1.8.0_162, the unlimited policy is enabled by default. You no longer need to install the policy file in the JRE or set the security property crypto.policy.openjdk bugs:Java 使⽤ AES-256 加密代码:1/**2 * @author xxx3 * @date 2020-09-16 11:174 **/5public class AES256Util {67/**8 * 密钥, 256位32个字节9*/10public static final String DEFAULT_SECRET_KEY = "uBdUx82vPHkDKb284d7NkjFoNcKWBuka";1112private static final String AES = "AES";1314/**15 * 初始向量IV, 初始向量IV的长度规定为128位16个字节, 初始向量的来源为随机⽣成.16*/17private static final byte[] KEY_VI = "c558Gq0YQK2QUlMc".getBytes();1819/**20 * 加密解密算法/加密模式/填充⽅式21*/22private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";2324private static java.util.Base64.Encoder base64Encoder = java.util.Base64.getEncoder();25private static java.util.Base64.Decoder base64Decoder = java.util.Base64.getDecoder();2627static {28 java.security.Security.setProperty("crypto.policy", "unlimited");29 }3031/**32 * AES加密33*/34public static String encode(String key, String content) {35try {36 javax.crypto.SecretKey secretKey = new javax.crypto.spec.SecretKeySpec(key.getBytes(), AES);37 javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CIPHER_ALGORITHM);38 cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, secretKey, new javax.crypto.spec.IvParameterSpec(KEY_VI)); 3940// 获取加密内容的字节数组(这⾥要设置为utf-8)不然内容中如果有中⽂和英⽂混合中⽂就会解密为乱码41byte[] byteEncode = content.getBytes(java.nio.charset.StandardCharsets.UTF_8);4243// 根据密码器的初始化⽅式加密44byte[] byteAES = cipher.doFinal(byteEncode);4546// 将加密后的数据转换为字符串47return base64Encoder.encodeToString(byteAES);48 } catch (Exception e) {49 e.printStackTrace();50 }51return null;52 }5354/**55 * AES解密56*/57public static String decode(String key, String content) {58try {59 javax.crypto.SecretKey secretKey = new javax.crypto.spec.SecretKeySpec(key.getBytes(), AES);60 javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CIPHER_ALGORITHM);61 cipher.init(javax.crypto.Cipher.DECRYPT_MODE, secretKey, new javax.crypto.spec.IvParameterSpec(KEY_VI)); 6263// 将加密并编码后的内容解码成字节数组64byte[] byteContent = base64Decoder.decode(content);65// 解密66byte[] byteDecode = cipher.doFinal(byteContent);67return new String(byteDecode, java.nio.charset.StandardCharsets.UTF_8);68 } catch (Exception e) {69 e.printStackTrace();70 }71return null;72 }7374public static void main(String[] args) {75 String dbPassword = "123456";76 String encryptDbPwd = AES256Util.encode(DEFAULT_SECRET_KEY, dbPassword);77 System.out.println("encrypt: " + encryptDbPwd);7879 String decrypt = AES256Util.decode(DEFAULT_SECRET_KEY, encryptDbPwd);80 System.out.println("decrypt:" + decrypt);81 }8283 }测试:最后特别说明⼀下:解密时⽤到的密钥, 初始向量IV, 加密模式, Padding模式必须和加密时的保持⼀致, 否则则会解密失败.。
java aes加密方法

java aes加密方法AES(Advanced Encryption Standard)是一种高级加密标准,是一种对称加密算法,用于数据的加密和解密。
它是目前被广泛使用的加密算法之一,安全性较高。
在Java中,可以使用JCE(Java Cryptography Extension)库来实现AES加密。
以下是使用Java实现AES加密的示例代码。
1. 导入JCE库在Java中,需要先导入JCE库才能使用AES加密。
在导入JCE库之前,需要在系统中安装Java的JDK(Java Development Kit)。
2. 生成密钥在AES加密中,需要使用一个密钥来加密和解密数据。
可以使用Java中的KeyGenerator类来生成一个随机的AES密钥。
例如:```KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");keyGenerator.init(128);SecretKey secretKey = keyGenerator.generateKey();byte[] keyBytes = secretKey.getEncoded();```此代码将生成一个128位(16字节)长度的随机密钥,存储在keyBytes变量中。
3. 初始化加密器接下来,需要使用已生成的密钥来初始化加密器。
可以使用Java中的Cipher类来实现这个过程。
例如:上面的代码将生成一个Cipher加密对象,并使用生成的密钥secretKeySpec来初始化加密器。
此时,加密器已准备好加密数据。
4. 加密数据接下来,可以使用加密器将数据进行加密。
可以将要加密的数据存储在byte数组中,然后将byte数组传递给加密器进行加密。
例如:```byte[] data = "Encrypt me".getBytes("UTF-8");byte[] encryptedData = cipher.doFinal(data);```上面的代码将字符串“Encrypt me”转换为UTF-8编码的byte数组,并将byte数组传递给加密器进行加密。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
JA V A实现AES加密算法代码近些年DES使用越来越少,原因就在于其使用56位密钥,比较容易被破解,近些年来逐渐被AES替代,AES已经变成目前对称加密中最流行算法之一;AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据。
本文就简单介绍如何通过JA VA实现AES加密。
1. JA V A 实现闲话少许,掠过AES加密原理及算法,关于这些直接搜索专业网站吧,我们直接看JA V A的具体实现。
1.1 加密代码有详细解释,不多废话。
/*** 加密** @param content 需要加密的内容* @param password 加密密码* @return*/public static byte[] encrypt(String content, String password) {try {KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey();byte[] enCodeFormat = secretKey.getEncoded();SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");Cipher cipher = Cipher.getInstance("AES");// 创建密码器byte[] byteContent = content.getBytes("utf-8");cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化byte[] result = cipher.doFinal(byteContent);return result; // 加密} catch (NoSuchAlgorithmException e){ e.printStackTrace();} catch (NoSuchPaddingException e) { e.printStackTrace();} catch (InvalidKeyException e) { e.printStackTrace();} catch (UnsupportedEncodingException e){ e.printStackTrace();} catch (IllegalBlockSizeException e) { e.printStackTrace();} catch (BadPaddingException e) { e.printStackTrace();} return null;}/*** 加密** @param content 需要加密的内容* @param password 加密密码* @return*/public static byte[] encrypt(String content, String password) {try {KeyGenerator kgen = KeyGenerator.getInstance("AES");kgen.init(128, new SecureRandom(password.getBytes()));SecretKey secretKey = kgen.generateKey();byte[] enCodeFormat = secretKey.getEncoded();SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");Cipher cipher = Cipher.getInstance("AES");// 创建密码器byte[] byteContent = content.getBytes("utf-8");cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化byte[] result = cipher.doFinal(byteContent);return result; // 加密} catch (NoSuchAlgorithmException e)(NoSuchPaddingException e) { e.printStackTrace();} catch (InvalidKeyException e) { e.printStackTrace();} catch (UnsupportedEncodingException e){ e.printStackTrace();} catch (IllegalBlockSizeException e) { e.printStackTrace();} catch (BadPaddingException e) { e.printStackTrace();} return null;} 2.2 解密代码有详细注释,不多废话注意:解密的时候要传入byte数组view plaincopy to clipboardprint?/**解密* @param content 待解密内容* @param password 解密密钥* @return*/ public static byte[] decrypt(byte[] content, String password) {try {KeyGenerator kgen =KeyGenerator.getInstance("AES");kgen.init(128, new SecureRandom(password.getBytes()));SecretKey secretKey = kgen.generateKey();byte[] enCodeFormat = secretKey.getEncoded();SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");Cipher cipher = Cipher.getInstance("AES");// 创建密码器cipher.init(Cipher.DECRYPT_MODE, key);// 初始化byte[] result = cipher.doFinal(content);return result; // 加密} catch (NoSuchAlgorithmException e)(NoSuchPaddingException e) { e.printStackTrace();} catch (InvalidKeyException e) { e.printStackTrace();} catch (IllegalBlockSizeException e){ e.printStackTrace();} catch (BadPaddingException e) { e.printStackTrace();}return null;}/**解密* @param content 待解密内容* @param password 解密密钥* @return*/public static byte[] decrypt(byte[] content, String password) {try {KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey();byte[] enCodeFormat = secretKey.getEncoded();SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");Cipher cipher = Cipher.getInstance("AES");// 创建密码器cipher.init(Cipher.DECRYPT_MODE, key);// 初始化byte[] result = cipher.doFinal(content);return result; // 加密} catch (NoSuchAlgorithmException e){ e.printStackTrace();} catch (NoSuchPaddingException e) { e.printStackTrace();} catch (InvalidKeyException e) { e.printStackTrace();} catch (IllegalBlockSizeException e){ e.printStackTrace();} catch (BadPaddingException e) { e.printStackTrace();}return null;}2.3 测试代码String content = "test";String password = "12345678";//加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password); //解密byte[] decryptResult =decrypt(encryptResult,password);System.out.println("解密后:" + new String(decryptResult));String content = "test"; String password = "12345678";//加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password);//解密byte[] decryptResult = decrypt(encryptResult,password); System.out.println("解密后:" + new String(decryptResult));输出结果如下:加密前:test解密后:test 2.4 容易出错的地方但是如果我们将测试代码修改一下,如下:String content = "test";String password = "12345678";//加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password); try {String encryptResultStr = newString(encryptResult,"utf-8");//解密byte[] decryptResult =decrypt(encryptResultStr.getBytes("utf-8"),password);System.out.println("解密后:" + newString(decryptResult));} catch (UnsupportedEncodingException e){ e.printStackTrace();}String content = "test"; String password = "12345678";//加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password);try{String encryptResultStr = newString(encryptResult,"utf-8");//解密byte[] decryptResult =decrypt(encryptResultStr.getBytes("utf-8"),password); System.out.println("解密后:" + newString(decryptResult));} catch (UnsupportedEncodingException e){ e.printStackTrace();}则,系统会报出如下异常:javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13* ..)at javax.crypto.Cipher.doFinal(DashoA13*..)这主要是因为加密后的byte数组是不能强制转换成字符串的,换言之:字符串和byte数组在这种情况下不是互逆的;要避免这种情况,我们需要做一些修订,可以考虑将二进制数据转换成十六进制表示,主要有如下两个方法: 2.4.1将二进制转换成16进制/**将二进制转换成16进制* @param buf* @return*/public static StringparseByte2HexStr(byte buf[]) {StringBuffer sb = new StringBuffer();for (int i = 0; i String hex = Integer.toHexString(buf[i] & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}sb.append(hex.toUpperCase());}returnsb.toString();}/**将二进制转换成16进制*@param buf* @return*/public static String parseByte2HexStr(byte buf[]) {StringBuffer sb = new StringBuffer();for (int i = 0; i String hex = Integer.toHexString(buf[i] & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}sb.append(hex.toUpperCase());}returnsb.toString();} 2.4.2 将16进制转换为二进制/**将16进制转换为二进制* @param hexStr* @return */public static byte[] parseHexStr2Byte(String hexStr){if (hexStr.length() return null;byte[] result = new byte[hexStr.length()/2];for (int i = 0;i int high =Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);result[i] = (byte) (high * 16 + low);}return result;}/**将16进制转换为二进制* @param hexStr*@return*/public static byte[] parseHexStr2Byte(String hexStr) {if (hexStr.length() return null;byte[] result = new byte[hexStr.length()/2];for (int i = 0;i int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16); result[i] = (byte) (high * 16 + low);}return result;}然后,我们再修订以上测试代码,如下:String content = "test";String password = "12345678";//加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password);String encryptResultStr = parseByte2HexStr(encryptResult); System.out.println("加密后:" + encryptResultStr);//解密byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);byte[] decryptResult = decrypt(decryptFrom,password); System.out.println("解密后:" + new String(decryptResult)); String content = "test";String password = "12345678";//加密System.out.println("加密前:" + content);byte[] encryptResult = encrypt(content, password);StringencryptResultStr = parseByte2HexStr(encryptResult); System.out.println("加密后:" + encryptResultStr);//解密byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);byte[] decryptResult = decrypt(decryptFrom,password); System.out.println("解密后:" + new String(decryptResult));测试结果如下:加密前:test加密后:73C58BAFE578C59366D8C995CD0B9D6D解密后:test 2.5 另外一种加密方式还有一种加密方式,大家可以参考如下:/*** 加密** @param content 需要加密的内容* @param password 加密密码*@return*/public static byte[] encrypt2(String content, String password) {try {SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");byte[] byteContent = content.getBytes("utf-8");cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化byte[] result = cipher.doFinal(byteContent);return result; // 加密} catch (NoSuchAlgorithmException e){ e.printStackTrace();} catch (NoSuchPaddingException e) { e.printStackTrace();} catch (InvalidKeyException e) { e.printStackTrace();} catch (UnsupportedEncodingException e){ e.printStackTrace();} catch (IllegalBlockSizeException e) { e.printStackTrace();} catch (BadPaddingException e) { e.printStackTrace();} return null;}/*** 加密** @param content 需要加密的内容* @param password 加密密码* @return*/public static byte[] encrypt2(String content, String password) {try {SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");byte[] byteContent = content.getBytes("utf-8");cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化byte[] result = cipher.doFinal(byteContent);return result; // 加密} catch (NoSuchAlgorithmException e){ e.printStackTrace();} catch (NoSuchPaddingException e) { e.printStackTrace();} catch (InvalidKeyException e) { e.printStackTrace();} catch (UnsupportedEncodingException e){ e.printStackTrace();} catch (IllegalBlockSizeException e) { e.printStackTrace();} catch (BadPaddingException e) { e.printStackTrace();} return null;}这种加密方式有两种限制密钥必须是16位的待加密内容的长度必须是16的倍数,如果不是16的倍数,就会出如下异常:javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes atcom.sun.crypto.provider.SunJCE_f.a(DashoA13*..)at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13* ..)at javax.crypto.Cipher.doFinal(DashoA13*..)要解决如上异常,可以通过补全传入加密内容等方式进行避免。