java - AES-CTR double encryption reverses the ciphertext to plaintext -


when try encrypt ciphertext again same key, produces original plaintext.

algoritm used aes counter mode. key , iv remains same.

is way algorithm supposed behave? , if, use of cipher.encrytmode given first parameter of cipher.init()?

here sample program 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, expected behavior. ctr mode of operation block ciphers makes stream cipher out of block cipher. since stream ciphers work in way generate keystream , xor keystream plaintext produce ciphertext:

plaintext xor aes-ctr(nonce, key) = ciphertext 

the xor operation works in way xoring x key k twice results in x again:

x ^ k ^ k = x 

this reason why encryption , decryption same operation block ciphers in ctr mode (sans nonce generation , putting ciphertext).

if don't want encryption , decryption algorithm same, should use different mode such cbc, there nothing wrong kind of thing.

beware ctr mode secure, have use different nonce/iv under same key every encryption.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -