【发布时间】:2016-08-21 14:18:33
【问题描述】:
我遇到了使用 java AES/CBC/PKCS7Padding 加密的问题。我已经搜索并关注直到使用BouncyCastle 提供程序。但我仍然无法获得正确的加密
假设要求是:
加密类型:对称
算法: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;
}
}
我仍然无法获得正确的加密。任何人都可以提供帮助或提供建议吗?
【问题讨论】:
-
我已经测试了你的代码,但我有一个例外。你测试过你的代码吗?也不例外?
-
问题,我只是不能像给我的例子那样得到正确的结果。代码已经剪掉了,先生,你不能只是复制粘贴来运行它。
标签: java encryption aes pkcs#7