AES/CBC 加密:添加了填充但仍然出现 IV 错误
AES/CBC Encryption: added padding but still getting IV error
我对加密还很陌生,我的任务是在向服务器验证之前加密密码(我知道这是不好的做法,但我必须遵守。)。这是我的加密方式:
public static String encrypt(String src) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Key key = makeKey();
AlgorithmParameterSpec iv = makeIv();
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return Base64.encodeBytes(cipher.doFinal(src.getBytes()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static AlgorithmParameterSpec makeIv() {
return new IvParameterSpec(ENCRYPTION_IV.getBytes(encoding));
}
static Key makeKey() {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] key = md.digest(ENCRYPTION_KEY.getBytes(encoding));
return new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
其中iv是由13个字符组成的字符串。我指定了填充,但为什么我仍然收到 InvalidAlgorithmParameterException: IV must be 16 bytes long.
错误?我如何真正实现这种加密方法?
填充仅适用于被加密的数据。数据几乎总是比您将其加密到的加密块 longer/shorter 少一点,因此最后一个块将需要一些填充。
但是你的 IV 需要 16 个字节,否则用零填充你的 IV 将是一个安全漏洞。
我对加密还很陌生,我的任务是在向服务器验证之前加密密码(我知道这是不好的做法,但我必须遵守。)。这是我的加密方式:
public static String encrypt(String src) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Key key = makeKey();
AlgorithmParameterSpec iv = makeIv();
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return Base64.encodeBytes(cipher.doFinal(src.getBytes()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static AlgorithmParameterSpec makeIv() {
return new IvParameterSpec(ENCRYPTION_IV.getBytes(encoding));
}
static Key makeKey() {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] key = md.digest(ENCRYPTION_KEY.getBytes(encoding));
return new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
其中iv是由13个字符组成的字符串。我指定了填充,但为什么我仍然收到 InvalidAlgorithmParameterException: IV must be 16 bytes long.
错误?我如何真正实现这种加密方法?
填充仅适用于被加密的数据。数据几乎总是比您将其加密到的加密块 longer/shorter 少一点,因此最后一个块将需要一些填充。
但是你的 IV 需要 16 个字节,否则用零填充你的 IV 将是一个安全漏洞。