JAVA实现AES加密算法代码
- 格式:doc
- 大小:40.00 KB
- 文档页数:11
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(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加密⼀、先看⼀个简单加密,解密实现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加密算法的代码:```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的加密和解密算法加密模式为 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实现字符串的加密、解密(配合⼆进制、⼗六进制转换的⼯具使⽤)//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 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加密方法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数组传递给加密器进行加密。
Java实现AES解密PKCS7填充256位的KEYjava中不支持采用AES加密算法PKCS7Padding来填充,只支持PKCS5Padding。
我们知道加密算法由算法+模式+填充组成,故不同的填充算法会导致相同明文相同密钥加密后出现密文不一致的情况。
实现在java端用PKCS7Padding填充,需用到bouncycastle组件来实现,Bouncy Castle是一种用于java平台的开放源码的轻量级密码术包,支持大量的密码术算法。
目录Java实现AES解密PKCS7填充256位的KEY (1)第一步、引入Bouncy Castle (1)第二步、写测试代码: ..................................................................... 错误!未定义书签。
1、代码实例 ................................................................................... 错误!未定义书签。
2、报错解决方案 (2)3、测试结果: (3)第一步、引入Bouncy Castle1、去官方站点(/latest_releases.html)下载Bouncy Castle 的JCE Provider包bcprov-ext-jdk15on-151.jar(最新版)2、把jar文件复制到$JAVA_HOME$\jre\lib\ext 目录下面3、修改配置文件\jre\lib\security\java.securitysecurity.provider.1=sun.security.provider.Sunsecurity.provider.2=sun.security.rsa.SunRsaSignsecurity.provider.3=sun.security.ec.SunECsecurity.provider.4=.ssl.internal.ssl.Providersecurity.provider.5=com.sun.crypto.provider.SunJCEsecurity.provider.6=sun.security.jgss.SunProvidersecurity.provider.7=com.sun.security.sasl.Providersecurity.provider.8=org.jcp.xml.dsig.internal.dom.XMLDSigRIsecurity.provider.9=sun.security.smartcardio.SunPCSCsecurity.provider.10=sun.security.mscapi.SunMSCAPI#前面是java环境已经提供的,尾部加上这两行行即可#增加BouncyCastleProvidersecurity.provider.11=org.bouncycastle.jce.provider.BouncyCastleProvider第二步、报错解决方案1、Access Restriction错误将网上这段代码复制进去后,会出错,错误类型:Access restriction: The type SecretKey is not accessible due to restriction on required library解决方案:Eclipse 默认把这些受访问限制的API设成了ERROR。
java ecieswithaes 加密案例ECIES(Elliptic Curve Integrated Encryption Scheme)结合AES (Advanced Encryption Standard)是一种结合椭圆曲线加密和对称密钥加密的加密方案。
在Java中,可以使用Bouncy Castle等库来实现ECIES和AES的结合加密。
下面是一个简单的Java示例,使用Bouncy Castle库进行ECIES和AES加密。
首先,确保你已经将Bouncy Castle库添加到你的Java项目中。
你可以在Maven 项目中通过以下方式添加依赖:<dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.68</version> <!-- 使用最新版本--> </dependency>接下来,可以使用以下代码进行ECIES和AES加密:import org.bouncycastle.crypto.AsymmetricCipherKeyPair;import org.bouncycastle.crypto.CipherParameters;import org.bouncycastle.crypto.InvalidCipherTextException;import org.bouncycastle.crypto.generators.ECKeyPairGenerator;importorg.bouncycastle.crypto.params.ECKeyGenerationParameters;import org.bouncycastle.crypto.params.ECKeyParameters;import org.bouncycastle.crypto.params.ECPrivateKeyParameters;import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.util.PublicKeyFactory;import org.bouncycastle.crypto.util.PrivateKeyFactory;import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Hex;import javax.crypto.Cipher;import java.security.KeyPair;import java.security.Security;import java.util.Arrays;public class ECIESWithAESExample {public static void main(String[] args) throws Exception { Security.addProvider(new BouncyCastleProvider());// 生成椭圆曲线密钥对AsymmetricCipherKeyPair keyPair = generateECKeyPair();// 明文消息String plainT ext = "Hello, ECIES with AES!";// 加密byte[] cipherText = encryptECIESWithAES(plainText, keyPair.getPublic());// 解密String decryptedText = decryptECIESWithAES(cipherT ext, keyPair.getPrivate());System.out.println("Original Text: " + plainText);System.out.println("Encrypted Text: " +Hex.toHexString(cipherText));System.out.println("Decrypted Text: " + decryptedText);}private static AsymmetricCipherKeyPair generateECKeyPair() { ECKeyPairGenerator generator = new ECKeyPairGenerator();ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(ECCurveParameters.createPrime256v1(), null);generator.init(keyGenParams);return generator.generateKeyPair();}private static byte[] encryptECIESWithAES(String plainText, ECKeyParameters publicKey) throws Exception {CipherParameters params =PublicKeyFactory.createKey(publicKey.getEncoded());// 使用椭圆曲线公钥进行ECIES加密ECIESWithCipherParameters eciesParams = new ECIESWithCipherParameters(params, "AES/GCM/NoPadding");// 加密Cipher cipher =Cipher.getInstance(eciesParams.getAlgorithmName(), BouncyCastleProvider.PROVIDER_NAME);cipher.init(Cipher.ENCRYPT_MODE, eciesParams);return cipher.doFinal(plainText.getBytes());}private static String decryptECIESWithAES(byte[] cipherText,ECKeyParameters privateKey) throws Exception {CipherParameters params =PrivateKeyFactory.createKey(privateKey.getEncoded());// 使用椭圆曲线私钥进行ECIES解密ECIESWithCipherParameters eciesParams = new ECIESWithCipherParameters(params, "AES/GCM/NoPadding");// 解密Cipher cipher =Cipher.getInstance(eciesParams.getAlgorithmName(), BouncyCastleProvider.PROVIDER_NAME);cipher.init(Cipher.DECRYPT_MODE, eciesParams);byte[] decryptedBytes = cipher.doFinal(cipherText);return new String(decryptedBytes);}}请注意,这个示例使用了Bouncy Castle库提供的椭圆曲线密钥生成和加密算法。
C#, Java, PHP, Python 和Javascript 的AES 加密解密实现c#里面的AES加密解密其中加密后以及解密后的字符串都能成功打印,但Console.WriteLine( =3== 之后的输出就没有了,最后输出个线程返回值0,然后就没有然后了。
c#不懂,就不深究了,就已执行的部分,是符合要求了。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Security.Cryptography;namespace testclass Class1static void Main(string[] args)Console.WriteLine( I am commingString source = Test StringString encryptData = Class1.Encrypt(source, 1234567812345678 , 1234567812345678Console.WriteLine( =1==Console.WriteLine(encryptData);Console.WriteLine( =2==String decryptData = Class1.Decrypt( 2fbwW9+8vPId2/foafZq6Q== , 1234567812345678 , 1234567812345678Console.WriteLine(decryptData);Console.WriteLine( =3==Console.WriteLine( I will go outpublic static string Encrypt(string toEncrypt, string key, string iv)byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);RijndaelManaged rDel = new RijndaelManaged();rDel.Key = keyArray;rDel.IV = ivArray;rDel.Mode = CipherMode.CBC;rDel.Padding = PaddingMode.Zeros;ICryptoTransform cTransform = rDel.CreateEncryptor();byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);return Convert.ToBase64String(resultArray, 0, resultArray.Length);public static string Decrypt(string toDecrypt, string key, string iv)byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);RijndaelManaged rDel = new RijndaelManaged();rDel.Key = keyArray;rDel.IV = ivArray;rDel.Mode = CipherMode.CBC;rDel.Padding = PaddingMode.Zeros;ICryptoTransform cTransform = rDel.CreateDecryptor();byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);return UTF8Encoding.UTF8.GetString(resultArray);}php的AES加密解密php代码,php很多东西都是提供好的,直接用函数,但是php目前所知填充模式只有ZeroPadding,于是其他语言就只能跟着它来了:php$privateKey = 1234567812345678$iv = 1234567812345678$data = Test String$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $data, MCRYPT_MODE_CBC, $iv);echo($encrypted);echo ‘ br/echo(base64_encode($encrypted));echo ‘ br/$encryptedData = base64_decode( 2fbwW9+8vPId2/foafZq6Q==$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $privateKey, $encryptedData, MCRYPT_MODE_CBC, $iv);echo($decrypted);Javascript下aes加解密需要在https:///p/crypto-js/下载工具包script type= text/javascript src= aes.js /scriptscript type= text/javascript src= pad-zeropadding.js /script导入文件,aes.js需要导入crypto-js压缩包中rollups文件夹下的那个aes.js文件,如果引入的是components文件夹下的aes.j s是会报错的script type= text/javascriptvar data = Test Stringvar key = tin1.parse(‘1234567812345678’);var iv = tin1.parse(‘1234567812345678’);//加密var encrypted = CryptoJS.AES.encrypt(data,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPad ding});document.write(encrypted.ciphertext);document.write(‘ br/document.write(encrypted.key);document.write(‘ br/document.write(encrypted.iv);document.write(‘ br/document.write(encrypted.salt);document.write(‘ br/document.write(encrypted);document.write(‘ br///解密var decrypted = CryptoJS.AES.decrypt(encrypted,key,{iv:iv,padding:CryptoJS.pad.ZeroPadding});console.log(decrypted.toString(CryptoJS.enc.Utf8));/scriptpython的AES加密解密最后加一个python下的aes,需要安装python Crypto:#!/usr/bin/env python# -*- coding: utf-8 -*-from Crypto.Cipher import AESimport base64PADDING = ‘\0’#PADDING = ‘ ‘pad_it = lambda s: s+(16 - len(s)%16)*PADDINGkey = ‘1234567812345678’iv = ‘1234567812345678’source = ‘Test String’generator = AES.new(key, AES.MODE_CBC, iv)crypt = generator.encrypt(pad_it(source))cryptedStr = base64.b64encode(crypt)print cryptedStrgenerator = AES.new(key, AES.MODE_CBC, iv)recovery = generator.decrypt(crypt)print recovery.rstrip(PADDING)注意python下需要用’\0’来填充,如果是空格来填充,python加密得到的字符串会跟其他语言不同。
在java项⽬中使⽤AES256CBC加密⾸先要注意⼀点,默认的JDK是不⽀持256位加密的,需要到Oracle官⽹下载加密增强⽂件(),否则编译会报错:java.security.InvalidKeyException: Illegal key size解压后替换jre/lib/security/⽬录下的同名⽂件即可。
最简单的应⽤实例:public class IotServer {private static final byte[] key = {..};//key.length须满⾜16的整数倍private static final byte[] iv = {..};//iv.length须满⾜16的整数倍private static final String transform = "AES/CBC/PKCS5Padding";private static final String algorithm = "AES";private static final SecretKeySpec keySpec = new SecretKeySpec(key, algorithm);public static void main(String[] args) {Cipher cipher = Cipher.getInstance(transform);cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));byte[] cipherData = cipher.doFinal("待加密的明⽂".getBytes("UTF-8"));System.out.println(Arrays.toString(cipherData));}}key和iv都可以通过更复杂的⽅式⽣成,⽅法很多这⾥不再列出,更多的使⽤技巧会在实际应⽤中发现。
AES加密算法java和js实现aes加密解密,AES加密⽐DES加密更安全1、页⾯引⼊js<script type="text/javascript" src="./aes/aes.js"></script><script type="text/javascript" src="./aes/mode-ecb.js"></script>2、AES加密⽅法//AES加密function Encrypt(word){var key = CryptoJS.enc.Utf8.parse("abcdefgabcdefg12");var srcs = CryptoJS.enc.Utf8.parse(word);var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7}); return encrypted.toString();}//AES解密function Decrypt(word){var key = CryptoJS.enc.Utf8.parse("abcdefgabcdefg12");var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7}); return CryptoJS.enc.Utf8.stringify(decrypt).toString();}测试:alert(Encrypt("测试"));alert(Decrypt(Encrypt("测试")));3、加密账号密码4、Java引⼊⼯具类(⽂章最后)5、使⽤⼯具类解密username=EncryptUtils.aesDecrypt(username, "abcdefgabcdefg12");password=EncryptUtils.aesDecrypt(password, "abcdefgabcdefg12");如果报错,试试:byte[] decryptFrom =EncryptUtils.parseHexStr2Byte(user);byte[] decryptResult = EncryptUtils.decrypt(decryptFrom, "abcdefgabcdefg12");user = new String(decryptResult);byte[] decryptFrom2 =EncryptUtils.parseHexStr2Byte(pwd);byte[] decryptResult2 = EncryptUtils.decrypt(decryptFrom2, "abcdefgabcdefg12");pwd = new String(decryptResult2);EncryptUtils.javapackage com.util;import java.math.BigInteger;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import mons.codec.binary.Base64;import ng.StringUtils;import sun.misc.BASE64Decoder;/*** 编码⼯具类* 实现aes加密、解密*/public class EncryptUtils {/*** 密钥*/private static final String KEY = "abcdefgabcdefg12";/*** 算法*/private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";// public static void main(String[] args) throws Exception {// String content = "ning11";// String password = "@#$#@!@#$#@!%^^%$";////加密// 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));// }/*** aes解密* @param encrypt 内容* @return* @throws Exception*/public static String aesDecrypt(String encrypt) throws Exception {return aesDecrypt(encrypt, KEY);}/*** aes加密* @param content* @return* @throws Exception*/public static String aesEncrypt(String content) throws Exception {return aesEncrypt(content, KEY);}/*** 将byte[]转为各种进制的字符串* @param bytes byte[]* @param radix 可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制 * @return转换后的字符串*/public static String binary(byte[] bytes, int radix){return new BigInteger(1, bytes).toString(radix);// 这⾥的1代表正数}/*** base 64 encode* @param bytes 待编码的byte[]* @return编码后的base 64 code*/public static String base64Encode(byte[] bytes){byte[] byte11 = Base64.encodeBase64(bytes);String byte1 = parseByte2HexStr(byte11);// return Base64.encodeBase64String(bytes);return byte1;}/**将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 String parseByte2HexStr(byte buf[]) {StringBuffer sb = new StringBuffer();for (int i = 0; i < buf.length; i++) {String hex = Integer.toHexString(buf[i] & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}sb.append(hex.toUpperCase());}return sb.toString();}/*** base 64 decode* @param base64Code 待解码的base 64 code* @return解码后的byte[]* @throws Exception*/public static byte[] base64Decode(String base64Code) throws Exception{return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code); }/*** AES加密* @param content 待加密的内容* @param encryptKey 加密密钥* @return加密后的byte[]* @throws Exception*/public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {KeyGenerator kgen = KeyGenerator.getInstance("AES");kgen.init(128);Cipher cipher = Cipher.getInstance(ALGORITHMSTR);cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));return cipher.doFinal(content.getBytes("utf-8"));}/*** AES加密为base 64 code* @param content 待加密的内容* @param encryptKey 加密密钥* @return加密后的base 64 code* @throws Exception*/public static String aesEncrypt(String content, String encryptKey) throws Exception {return base64Encode(aesEncryptToBytes(content, encryptKey));}/*** AES解密* @param encryptBytes 待解密的byte[]* @param decryptKey 解密密钥* @return解密后的String* @throws Exception*/public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES");kgen.init(128);Cipher cipher = Cipher.getInstance(ALGORITHMSTR);cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));byte[] decryptBytes = cipher.doFinal(encryptBytes);return new String(decryptBytes);}* 将base 64 code AES解密* @param encryptStr 待解密的base 64 code* @param decryptKey 解密密钥* @return解密后的string* @throws Exception*/public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);}/**解密* @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 (Exception e) {e.printStackTrace();}return null;}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 (Exception e) {e.printStackTrace();}return null;}}Base64.javapackage com.zbiti.android.zhxj.activity;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;public class Base64 {private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); /*** data[]进⾏编码* @param data* @return*/public static String encode(byte[] data) {int start = 0;int len = data.length;StringBuffer buf = new StringBuffer(data.length * 3 / 2);int end = len - 3;int i = start;int n = 0;while (i <= end) {int d = ((((int) data[i]) & 0x0ff) << 16)| ((((int) data[i + 1]) & 0x0ff) << 8)| (((int) data[i + 2]) & 0x0ff);buf.append(legalChars[(d >> 18) & 63]);buf.append(legalChars[(d >> 12) & 63]);buf.append(legalChars[(d >> 6) & 63]);buf.append(legalChars[d & 63]);i += 3;if (n++ >= 14) {n = 0;buf.append(" ");}}if (i == start + len - 2) {int d = ((((int) data[i]) & 0x0ff) << 16)| ((((int) data[i + 1]) & 255) << 8);buf.append(legalChars[(d >> 18) & 63]);buf.append(legalChars[(d >> 12) & 63]);buf.append(legalChars[(d >> 6) & 63]);buf.append("=");} else if (i == start + len - 1) {int d = (((int) data[i]) & 0x0ff) << 16;buf.append(legalChars[(d >> 18) & 63]);buf.append(legalChars[(d >> 12) & 63]);buf.append("==");}return buf.toString();}private static int decode(char c) {if (c >= 'A' && c <= 'Z')return ((int) c) - 65;else if (c >= 'a' && c <= 'z')return ((int) c) - 97 + 26;else if (c >= '0' && c <= '9')return ((int) c) - 48 + 26 + 26;elseswitch (c) {case '+':return 62;case '/':return 63;case '=':return 0;default:throw new RuntimeException("unexpected code: " + c);}}/*** Decodes the given Base64 encoded String to a new byte array. The byte * array holding the decoded data is returned.*/public static byte[] decode(String s) {ByteArrayOutputStream bos = new ByteArrayOutputStream();try {decode(s, bos);} catch (IOException e) {throw new RuntimeException();}byte[] decodedBytes = bos.toByteArray();try {bos.close();bos = null;} catch (IOException ex) {System.err.println("Error while decoding BASE64: " + ex.toString()); }return decodedBytes;}private static void decode(String s, OutputStream os) throws IOException {int i = 0;int len = s.length();while (true) {while (i < len && s.charAt(i) <= ' ')i++;if (i == len)break;int tri = (decode(s.charAt(i)) << 18)+ (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6) + (decode(s.charAt(i + 3)));os.write((tri >> 16) & 255);if (s.charAt(i + 2) == '=')break;os.write((tri >> 8) & 255);if (s.charAt(i + 3) == '=')break;os.write(tri & 255);i += 4;}}}。
JavaAES256加密解密⽰例代码Java⽀持许多安全的加密算法,但是其中⼀些功能较弱,⽆法在安全性要求很⾼的应⽤程序中使⽤。
例如,数据加密标准(DES)加密算法被认为是⾼度不安全的。
今天介绍⼀下AES 256加密解密。
什么是 AES 256?⾼级加密标准(英语:Advanced Encryption Standard,缩写:AES ),在密码学中⼜称Rijndael加密法,是美国联邦政府采⽤的⼀种区块加密标准。
这个标准⽤来替代原先的DES,已经被多⽅分析且⼴为全世界所使⽤。
AES是⼀种对称加密算法。
它旨在易于在硬件和软件以及受限环境中实施,并提供针对各种攻击技术的良好防御。
AES 是能够使⽤⼤⼩为128、192和256位的密钥处理128位块的块密码。
每个密码分别使⽤128位,192位和256位的加密密钥对128位块中的数据进⾏加密和解密。
它使⽤相同的密钥进⾏加密和解密,因此发送⽅和接收⽅都必须知道并使⽤相同的秘密密钥。
在下⾯的加密和解密⽰例中,我在UTF-8字符集中使⽤了base64编码。
⽤于显⽰程序的输出。
也可以以字节数组格式存储和验证数据。
AES 256加密Java程序中,⽤于使⽤AES 256位对密码(或任何信息)进⾏加密。
private static String secretKey = "boooooooooom";private static String salt = "ssshhhhhhhhhhh";public static String encrypt(String strToEncrypt, String secret){try{byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };IvParameterSpec ivspec = new IvParameterSpec(iv);SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);SecretKey tmp = factory.generateSecret(spec);SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));}catch (Exception e){System.out.println("Error while encrypting: " + e.toString());}return null;}AES 256解密Java程序,⽤于使⽤AES 256位解密密码(或任何信息)。
Java使⽤Hutool实现AES、DES加密解密的⽅法在Java世界中,AES、DES加密解密需要使⽤Cipher对象构建加密解密系统,Hutool中对这⼀对象做再包装,简化了加密解密过程。
介绍AES和DES同属对称加密算法,数据发信⽅将明⽂(原始数据)和加密密钥⼀起经过特殊加密算法处理后,使其变成复杂的加密密⽂发送出去。
收信⽅收到密⽂后,若想解读原⽂,则需要使⽤加密⽤过的密钥及相同算法的逆算法对密⽂进⾏解密,才能使其恢复成可读明⽂。
在对称加密算法中,使⽤的密钥只有⼀个,发收信双⽅都使⽤这个密钥对数据进⾏加密和解密,这就要求解密⽅事先必须知道加密密钥。
在Java世界中,AES、DES加密解密需要使⽤Cipher对象构建加密解密系统,Hutool中对这⼀对象做再包装,简化了加密解密过程。
引⼊Hutool<dependency><groupId>com.xiaoleilu</groupId><artifactId>hutool-all</artifactId><version>3.0.9</version></dependency>使⽤AES加密解密String content = "test中⽂";//随机⽣成密钥byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();//构建AES aes = SecureUtil.aes(key);//加密byte[] encrypt = aes.encrypt(content);//解密byte[] decrypt = aes.decrypt(encrypt);//加密为16进制表⽰String encryptHex = des.encryptHex(content);//解密为原字符串String decryptStr = des.decryptStr(encryptHex);DES加密解密DES的使⽤⽅式与AES基本⼀致String content = "test中⽂";//随机⽣成密钥byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue()).getEncoded();//构建DES des = SecureUtil.des(key);//加密解密byte[] encrypt = des.encrypt(content);byte[] decrypt = des.decrypt(encrypt);//加密为16进制,解密为原字符串String encryptHex = des.encryptHex(content);String decryptStr = des.decryptStr(encryptHex);更多Hutool中针对JDK⽀持的所有对称加密算法做了封装,封装为SymmetricCrypto类,AES和DES两个类是此类的简化表⽰。
Java中的AES加密(SHA1PRNG)转换为C# Java代码:1 KeyGenerator aesGen = KeyGenerator.getInstance("AES");2 SecureRandom secureRadmon= new SecureRandom().getInstance("SHA1PRNG");3 secureRadmon.setSeed(aesKey.getBytes());4 aesGen.init(128,secureRadmon);5 SecretKey secretKey =aesGen.generateKey();.Net(C#)代码:1byte[] keyArray = null;2using (var sha1 = new SHA1CryptoServiceProvider())3 {4byte[] hash = puteHash(Encoding.UTF8.GetBytes(aesKey));5var rd = puteHash(hash);6 keyArray = rd.Take(16).ToArray();7 }------------------附对应的AES/ECB/PKCS5Padding加密-----------------------1private static string encryptAES(string keyStr)2 {3byte[] plainText = System.Text.Encoding.UTF8.GetBytes(keyStr);4 Base64Encoder encoder = new Base64Encoder();5 RijndaelManaged AesCipher = new RijndaelManaged();6 AesCipher.KeySize = 128; // 192, 2567 AesCipher.BlockSize = 128;8 AesCipher.Mode = CipherMode.ECB;9 AesCipher.Padding = PaddingMode.PKCS7;10//AesCipher.IV = keyArray;11//AesCipher.Key = keyArray;12 ICryptoTransform crypto = AesCipher.CreateEncryptor();13byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);14string aesBase64 = Regex.Replace(encoder.GetEncoded(cipherText), @"[\r\n]+", "");15return aesBase64;16 }View Code>>>>>>>>>>1///<summary>2/// Base64编码类。
Java实现AESCBCPKCS7Padding加解密的⽅法最近项⽬需要选择⼀套对称加密算法,来满⾜前后端之间的加解密操作。
初步打算前端使⽤crypto-js来实现,后端使⽤java本⾝的加密算法实现,但遇到了⼀个问题:java本⾝只⽀持NoPadding和PKCS5Padding,⽽crypto-js提供的padding⽅式没有PKCS5Padding,所以不得以,前后端最终使⽤PKCS7Padding来实现功能.因此只能通过引⼊第三⽅jar包的⽅式让jave⽀持pkcs7padding引⼊依赖<dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk16</artifactId><version>1.46</version></dependency>完整代码package com.hzjd.miniapp.util;import java.security.Security;import java.security.spec.AlgorithmParameterSpec;import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import mons.codec.binary.Base64;import ng.StringUtils;import org.bouncycastle.jce.provider.BouncyCastleProvider;import com.sun.istack.internal.NotNull;public class AESUtil {private static final String CHARSET_NAME = "UTF-8";private static final String AES_NAME = "AES";// 加密模式public static final String ALGORITHM = "AES/CBC/PKCS7Padding";// 密钥public static final String KEY = "1954682168745975";// 偏移量public static final String IV = "1954682168745975";static {Security.addProvider(new BouncyCastleProvider());}/*** 加密** @param content* @param key* @return*/public String encrypt(@NotNull String content) {byte[] result = null;try {Cipher cipher = Cipher.getInstance(ALGORITHM);SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(CHARSET_NAME), AES_NAME);AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV.getBytes());cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec);result = cipher.doFinal(content.getBytes(CHARSET_NAME));} catch (Exception e) {e.printStackTrace();}return Base64.encodeBase64String(result);}/*** 解密** @param content* @param key* @return*/public String decrypt(@NotNull String content) {try {Cipher cipher = Cipher.getInstance(ALGORITHM);SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(CHARSET_NAME), AES_NAME);AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV.getBytes());cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);return new String(cipher.doFinal(Base64.decodeBase64(content)), CHARSET_NAME);} catch (Exception e) {e.printStackTrace();}return StringUtils.EMPTY;}public static void main(String[] args) {AESUtil aes = new AESUtil();String contents = "121456465";String encrypt = aes.encrypt(contents);System.out.println("加密后:" + encrypt);String decrypt = aes.decrypt(encrypt);System.out.println("解密后:" + decrypt);}}总结到此这篇关于Java实现AES/CBC/PKCS7Padding加解密的⽅法的⽂章就介绍到这了,更多相关Java实现AES/CBC/PKCS7Padding加解密内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
JAVA实现AES加密算法代码JA V A实现AES加密算法代码近些年DES使用越来越少,原因就在于其使用56位密钥,比较容易被破解,近些年来逐渐被AES替代,AES已经变成目前对称加密中最流行算法之一;AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据。
本文就简单介绍如何通过JA V A实现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);// 初始化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;}/**解密* @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 atcom.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA 13*..)at javax.crypto.Cipher.doFinal(DashoA13*..)这主要是因为加密后的byte数组是不能强制转换成字符串的,换言之:字符串和byte数组在这种情况下不是互逆的;要避免这种情况,我们需要做一些修订,可以考虑将二进制数据转换成十六进制表示,主要有如下两个方法: 2.4.1将二进制转换成16进制/**将二进制转换成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();}/**将二进制转换成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();} 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);intlow = 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);intlow = 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);String encryptResultStr = parseByte2HexStr(encryptResult); System.out.println("加密后:" + encryptResultStr);//解密byte[] decryptFrom =parseHexStr2Byte(encryptResultStr);byte[] decryptResult = decrypt(decryptFrom,password); System.out.println("解密后:" + new String(decryptResult));测试结果如下:加密前:test加密后:73C58BAFE578C59366D8C995CD0B9D6D解密后:test2.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 = newSecretKeySpec(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(DashoA 13*..)at javax.crypto.Cipher.doFinal(DashoA13*..)要解决如上异常,可以通过补全传入加密内容等方式进行避免。
AESJava加密C#解密(128-ECB加密模式)在项⽬中遇到这么⼀个问题:java端需要把⼀些数据AES加密后传给C#端,找了好多资料,算是解决了,分享⼀下:import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import java.security.SecureRandom;public class AesEncodeUtil {private final static String transferKey ="qazwsxedcrfv12345";public static void main(String[] args) throws Exception {String a = aesTransferEncrypt("QAZwsx123!@#$%^&*");System.out.println(a);System.out.println(aesTransferDncrypt(a));}/*** 传输⽤加密* @param content* @return* @throws Exception*/public static String aesTransferEncrypt(String content) throws Exception {return base64Encode(aesEncryptToBytes(content, transferKey));}/*** 传输⽤解密* @param content* @return* @throws Exception*/public static String aesTransferDncrypt(String encryptStr) throws Exception {return aesDecryptByBytes(base64Decode(encryptStr), transferKey);}/*** base 64 encode* @param bytes 待编码的byte[]* @return 编码后的base 64 code*/private static String base64Encode(byte[] bytes) {return new BASE64Encoder().encode(bytes);}/*** base 64 decode* @param base64Code 待解码的base 64 code* @return 解码后的byte[]* @throws Exception*/private static byte[] base64Decode(String base64Code) throws Exception {return new BASE64Decoder().decodeBuffer(base64Code);}/*** AES加密* @param content 待加密的内容* @param encryptKey 加密密钥* @return 加密后的byte[]* @throws Exception*/private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {KeyGenerator kgen = KeyGenerator.getInstance("AES");SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );secureRandom.setSeed(encryptKey.getBytes());kgen.init(128, secureRandom);Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.ENCRYPT_MODE, kgen.generateKey());return cipher.doFinal(content.getBytes("UTF-8"));}/*** AES解密* @param encryptBytes 待解密的byte[]* @param decryptKey 解密密钥* @return 解密后的String* @throws Exception*/private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {KeyGenerator kgen = KeyGenerator.getInstance("AES");SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );secureRandom.setSeed(decryptKey.getBytes());kgen.init(128, secureRandom);Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.DECRYPT_MODE,kgen.generateKey());byte[] decryptBytes = cipher.doFinal(encryptBytes);return new String(decryptBytes,"UTF-8");}}java代码加密/解密运⾏结果:加密结果:BKscOr7eK4jTO5Hcw5oxqS8HWg2SRhtGfMctz8t/45g=解密结果:QAZwsx123!@#$%^&*再看看C#代码:///<summary>/// AES加密 (128-ECB加密模式)///</summary>///<param name="toEncrypt">内容</param>///<param name="key">秘钥</param>///<returns></returns>public static string AESEncrypt(string toEncrypt, string key){byte[] keyArray = Convert.FromBase64String(key);byte[] toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt);RijndaelManaged rDel = new RijndaelManaged();rDel.Key = keyArray;rDel.Mode = CipherMode.ECB;rDel.Padding = PaddingMode.PKCS7;ICryptoTransform cTransform = rDel.CreateEncryptor();byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);return Convert.ToBase64String(resultArray, 0, resultArray.Length);}///<summary>/// AES解密(128-ECB加密模式)///</summary>///<param name="toDecrypt">密⽂</param>///<param name="key">秘钥(Base64String)</param>///<returns></returns>public static string AESDecrypt(string toDecrypt, string key){try{byte[] keyArray = Convert.FromBase64String(key); //128bitbyte[] toEncryptArray = Convert.FromBase64String(toDecrypt);RijndaelManaged rDel = new RijndaelManaged();rDel.Key = keyArray; //获取或设置对称算法的密钥rDel.Mode = CipherMode.ECB; //获取或设置对称算法的运算模式,必须设置为ECBrDel.Padding = PaddingMode.PKCS7; //获取或设置对称算法中使⽤的填充模式,必须设置为PKCS7ICryptoTransform cTransform = rDel.CreateDecryptor(); //⽤当前的 Key 属性和初始化向量 (IV) 创建对称解密器对象byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);return Encoding.UTF8.GetString(resultArray);}catch{return null;}}但是如果直接把 transferKey ="qazwsxedcrfv12345" 和加密结果:BKscOr7eK4jTO5Hcw5oxqS8HWg2SRhtGfMctz8t/45g=给C#,C#是⽆法解密的,因为 rDel.Key = keyArray; 会报错。
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*..)要解决如上异常,可以通过补全传入加密内容等方式进行避免。