最近项目需要选择一套对称加密算法,来满足前后端之间的加解密操作。初步打算前端使用crypto-js来实现,后端使用java本身的加密算法实现,但遇到了一个问题:java本身只支持nopadding和pkcs5padding,而crypto-js提供的padding方式没有pkcs5padding,所以不得以,前后端最终使用pkcs7padding来实现功能.因此只能通过引入第三方jar包的方式让jave支持pkcs7padding
引入依赖
org.bouncycastle
bcprov-jdk16
1.46
完整代码
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 org.apache.commons.codec.binary.base64;
import org.apache.commons.lang.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加解密内容请搜索萬仟网以前的文章或继续浏览下面的相关文章希望大家以后多多支持萬仟网!
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!