简体   繁体   中英

AES-CTR double encryption reverses the ciphertext to plaintext

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM