我想了解更多关于AES加密的信息。 AES加密使用密钥和IV进行加密,但由于每个IV都不同,AES如何解密密文并返回明文?AES如何解密不同的IV?
http://www.moserware.com/2009/09/stick-figure-guide-to-advanced.html https://www.securecoding.cert.org/confluence/display/java/MSC61-J.+Do+not+use+insecure+or+weak+cryptographic+algorithms
public static byte[] encrypt_cbc(SecretKey skey, String plaintext) {
/* Precond: skey is valid; otherwise IllegalStateException will be thrown. */
try {
byte[] ciphertext = null;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
final int blockSize = cipher.getBlockSize();
byte[] initVector = new byte[blockSize];
(new SecureRandom()).nextBytes(initVector);
IvParameterSpec ivSpec = new IvParameterSpec(initVector);
cipher.init(Cipher.ENCRYPT_MODE, skey, ivSpec);
byte[] encoded = plaintext.getBytes(java.nio.charset.StandardCharsets.UTF_8);
ciphertext = new byte[initVector.length + cipher.getOutputSize(encoded.length)];
for (int i=0; i < initVector.length; i++) {
ciphertext[i] = initVector[i];
}
// Perform encryption
cipher.doFinal(encoded, 0, encoded.length, ciphertext, initVector.length);
return ciphertext;
} catch (NoSuchPaddingException | InvalidAlgorithmParameterException | ShortBufferException |
BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException e)
{
/* None of these exceptions should be possible if precond is met. */
throw new IllegalStateException(e.toString());
}
}
public static String decrypt_cbc(SecretKey skey, byte[] ciphertext)
throws BadPaddingException, IllegalBlockSizeException /* these indicate corrupt or malicious ciphertext */
{
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
final int blockSize = cipher.getBlockSize();
byte[] initVector = Arrays.copyOfRange(ciphertext, 0, blockSize);
IvParameterSpec ivSpec = new IvParameterSpec(initVector);
cipher.init(Cipher.DECRYPT_MODE, skey, ivSpec);
byte[] plaintext = cipher.doFinal(ciphertext, blockSize, ciphertext.length - blockSize);
return new String(plaintext);
} catch (NoSuchPaddingException | InvalidAlgorithmParameterException |
InvalidKeyException | NoSuchAlgorithmException e)
{
/* None of these exceptions should be possible if precond is met. */
throw new IllegalStateException(e.toString());
}
}
嗯,我认识到我的异常处理,我认为,但我绝不会在我的方法名称中使用下划线或删除catch块中的整个堆栈跟踪。或者现在然后使用'final'。或者给密文分配'null'。或者仍然使用CBC。关于代码实践,这并不是一个很好的例子。虽然可能会恶化很多! –
@youcanlearnanything *“AES如何用**不同的** IV解密?”* - 你能举一个你看过这个的例子吗? IV对于一个加密/解密周期 –
@ ArtjomB必须相同。如果这意味着什么,那么可能是因为纯运气或者IV仅部分不同(它与明文异或,所以),前16个字节有点意义。如果IV不同,只有第一个块受到影响。 –