Flask接口签名sign原理与实例代码浅析
333
2022-08-27
Java实现AES算法的实例代码
使用AES算法可用于对数据进行加密码与解密,使用的时候需要注意两点:1)被加密的串越长,加密后的字符串越长,注意数据库字段的设计;2)linux与Windows环境中可能会出现由于环境差异导致在Windows中测试成功,到Linux上后加密的串无法被正确解密。下列算法已在真实环境中进行实测,应用时也务必做好二次验证避免出现线上事故。
补充:下面看下java使用AES算法的实例代码。
Java中使用AES(CBC,128位)算法加解密。一般加密后都是用一定编码格式进行传输,此处使用Base64算法进行编解码。实现及测试代码如下:
AESUtil.java
package gj.secure;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;
public class AESUtil {
private static final String CIPHER_ALGORITHM_CBC = "AES/CBC/PKCS5Padding";
private static final String KEY_ALGORITHM = "AES";
public static byte[] initKey() throws Exception {
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
kg.init(128);
SecretKey secretKey = kg.generateKey();
return secretKey.getEncoded();
}
public static byte[] encrypt(byte[] data, byte[] key, byte[] iv) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
Key k = new SecretKeySpec(key, KEY_ALGORITHM);
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, k, paramSpec);
return cipher.doFinal(data);
public static byte[] decrypt(byte[] bytes, byte[] key, byte[] iv) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, k, paramSpec);
return cipher.doFinal(bytes);
public static String encodeToBase64String(String data, byte[] key, byte[] iv) throws Exception {
return Base64.getEncoder().encodeToString(encrypt(data.getBytes(), key, iv));
public static String decodeFromBase64String(String data, byte[] key, byte[] iv) throws Exception {
byte[] bytes = Base64.getDecoder().decode(data);
return new String(decrypt(bytes, key, iv));
}
测试代码:
AESUtilTest.java
package gj.secure;
/**
* created by gj on 2019-12-24 17:17
**/
public class AESUtilTest {
public static void main(String[] args) throws Exception {
byte[] key = AESUtil.initKey();
byte[] iv = {0x01, 0x23, 0x45, 0x67, 0x89 - 0xFF, 0xAB - 0xFF, 0xCD - 0xFF, 0xEF - 0xFF,
0x01, 0x23, 0x45, 0x67, 0x89 - 0xFF, 0xAB - 0xFF, 0xCD - 0xFF, 0xEF - 0xFF};
String content = "areful1997";
String cipher = AESUtil.encodeToBase64String(content, key, iv);
System.out.println(cipher);
String plain = AESUtil.decodeFromBase64String(cipher, key, iv);
System.out.println(plain);
}
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~