我想了解更多關於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不同,只有第一個塊受到影響。 –