Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
When I try to encrypt the ciphertext again with the same key, it produces the original plaintext.
Algoritm used is
AES
with
COUNTER MODE
.
Key
and
IV
remains the same.
Is this the way the algorithm is supposed to behave? And if, what is the use of
Cipher.ENCRYTMODE
which is to be given as the first parameter of Cipher.init()?
Here is the sample program with which I tested,
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class EncryptionTest {
public static void main(String[] args) throws Exception {
SecretKeySpec key = null;
IvParameterSpec ivSpec = null;
byte[] keyBytes = "usethiskeyusethiusethiskeyusethi".getBytes();
byte[] ivBytes = "usethisIusethisI".getBytes();
key = new SecretKeySpec(keyBytes, "AES"); //No I18N
ivSpec = new IvParameterSpec(ivBytes);
Cipher AesCipher = Cipher.getInstance("AES/CTR/NoPadding");
byte[] byteText = "Your Plain Text Here".getBytes();
AesCipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] byteCipherText = AesCipher.doFinal(byteText);
System.out.println("Encrypted : " + new String(byteCipherText));
AesCipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] bytePlainText = AesCipher.doFinal(byteCipherText);
System.out.println("Double Encrypted : " + new String(bytePlainText));
Yes, that is expected behavior. The CTR mode of operation for block ciphers makes a stream cipher out of a block cipher. Since stream ciphers work in a way that they generate a keystream and XOR the keystream with the plaintext to produce the ciphertext:
plaintext XOR AES-CTR(nonce, key) = ciphertext
The XOR operation works in a way where XORing x
with a key k
twice results in x
again:
x ^ k ^ k = x
This is the reason why encryption and decryption are exactly the same operation for block ciphers in CTR mode (sans nonce generation and putting it into the ciphertext).
If you don't want that the encryption and decryption algorithm are the same, then you should use a different mode such as CBC, but there is nothing wrong with this kind of thing.
Beware that for CTR mode to be secure, you have to use a different nonce/IV under the same key for every encryption.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.