[英]JAVA Encryption with AES/CBC/PKCS7Padding
我在使用 java AES/CBC/PKCS7Padding 進行加密時遇到了問題。 我已經搜索並關注了直到使用BouncyCastle
提供商。 但我仍然無法獲得正確的加密
假設要求是:
加密類型:對稱
算法:AES
塊大小 = 128Bit(16 字節)
密碼模式:CBC
填充模式:PKCS7
加密密鑰長度:256 Bit (32 Bytes)
向量初始化長度 (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 對密鑰長度的限制:由於美國不允許使用硬安全密鑰,因此默認情況下 Java 的密鑰長度限制為 128 位。
要啟用大於 128 位的密鑰,您必須使用官方的“無限”策略( 此處針對 SE8 )更改 Java 版本的策略
使用下載覆蓋 lib/security 中的當前策略就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.