javaaes填充_java中使⽤AES加密(加密模式为CBC,填充⽅
式:AESCBCPK。。。
⾸先导⼊依赖
commons-codec
commons-codec
⼯具类
import dec.binary.Base64;
pto.Cipher;
pto.spec.IvParameterSpec;
pto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Security;
/**
* AES加解密⼯具
*/
public class EncryptUtil {
private static final String CipherMode="AES/CBC/PKCS7Padding";
private static final String SecretKey="key";
private static final Integer IVSize=16;
private static final String EncryptAlg ="AES";
private static final String Encode="UTF-8";
private static final int SecretKeySize=32;
private static final String Key_Encode="UTF-8";
/**
* 创建密钥
* @return
*/
private static SecretKeySpec createKey(){
StringBuilder sb=new StringBuilder(SecretKeySize);
sb.append(SecretKey);
if (sb.length()>SecretKeySize){
sb.setLength(SecretKeySize);
}
if (sb.length()
while (sb.length()
sb.append(" ");
}
}
try {
byte[] String().getBytes(Encode); return new SecretKeySpec(data, EncryptAlg); }catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 创建16位向量: 不够则⽤0填充
* @return
*/
private static IvParameterSpec createIV() { StringBuffer sb = new StringBuffer(IVSize); sb.append(SecretKey);
if (sb.length()>IVSize){
sb.setLength(IVSize);
}
if (sb.length()
while (sb.length()
sb.append("0");
}
}
byte[] data=null;
try {
String().getBytes(Encode);
} catch (UnsupportedEncodingException e) { e.printStackTrace();
}
return new IvParameterSpec(data);
}
/**
* 加密:有向量16位,结果转base64
* @param context
* @return
*/
public static String encrypt(String context) {
try {
//下⾯这⾏在进⾏PKCS7Padding加密时必须加上,否则报错
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] Bytes(Encode);
SecretKeySpec key = createKey();
Cipher cipher = Instance(CipherMode);
cipher.init(Cipher.ENCRYPT_MODE, key, createIV());
byte[] data = cipher.doFinal(content);
String result= deBase64String(data);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
* @param context
* @return
*/
public static String decrypt(String context) {
try {
byte[] data=Base64.decodeBase64(context);
SecretKeySpec key = createKey();
Cipher cipher = Instance(CipherMode);
cipher.init(Cipher.DECRYPT_MODE, key, createIV());
byte[] content = cipher.doFinal(data);
String result=new String(content,Encode);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}java加密方式有哪些
注意:PKCS7Padding加密时需要调⽤BouncyCastleProvider让java⽀持PKCS7Padding 相应的依赖
org.bouncycastle
bcprov-jdk16
1.46

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。