使用java AES/CBC/PKCS7Padding进行加密时出现问题。我已经搜索并遵循通过使用BouncyCastle
供应商。但我仍然无法得到正确的加密使用AES/CBC/PKCS7Padding进行JAVA加密
咱们说的要求是:
加密类型:对称
算法:AES
块大小= 128位(16个字节)
加密模式:CBC
填充模式:PKCS7
加密密钥长度:256位(32个字节)
向量初始化长度(IV):128位(16个字节)
样本:
纯文本数据= ABC123
加密数据(base64编码)= CtGtW4hJfXxilSfNR1xmrg ==
和我的代码是...
public final class StringFunc {
final static String key = "jb2a19ou79rws6zknjlr803fvfgiyp1k";
final static String algorithm = "AES/CBC/PKCS7Padding";
final static String iv = "hod74ty97wr97g83";
private static Cipher cipher = null;
private static SecretKeySpec skeySpec = null;
private static IvParameterSpec ivSpec = null;
private static void setUp(){
try{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
skeySpec = new SecretKeySpec(key.getBytes(), "AES");
ivSpec = new IvParameterSpec(iv.getBytes());
cipher = Cipher.getInstance(algorithm);
}catch(NoSuchAlgorithmException | NoSuchPaddingException ex){
}
}
public static String encrypt(String str){
try{
Integer strL = (int) Math.ceil(str.length()/8.0);
Integer strB = strL*8;
str = padRight(str, '', strB);
setUp();
try {
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
} catch (InvalidAlgorithmParameterException ex) {
return "";
}
byte[] enc = cipher.doFinal(str.getBytes());
return new String(Base64.encodeBase64(enc));
}catch(InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex){
return "";
}
}
public static String padRight(String msg, char x, int l) {
String result = "";
if (!msg.isEmpty()) {
for (int i=0; i<(l-msg.length()); i++) {
result = result + x;
}
result = msg + result;
}
return result;
}
}
我仍然无法得到正确的加密。任何人都可以提供帮助或给出建议?
什么问题? –
我测试了你的代码,我有个例外。你测试了你的代码?没有例外 ? –
的问题,我只是不能得到正确的结果,就像给我的例子。由于原因,代码已经被删除,因此您不能仅仅复制粘贴来运行它。 – lendir