Java: AES encryption using CTR mode; Unable to decrypt
                                        
                    •
                    Java                                    
                I'm using the following code, but it doesn't decrypt the text correctly. What I get is output
Encryption:% no2f? ¢¶SHºûÅ“? ¾
Plaintext: Hello × amoriginÎl
public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    // Dernier exemple CTR mode
    // Clé 16 bits
    byte[] keyBytes = new byte[] { (byte) 0x36,(byte) 0xf1,(byte) 0x83,(byte) 0x57,(byte) 0xbe,(byte) 0x4d,(byte) 0xbd,(byte) 0x77,(byte) 0xf0,(byte) 0x50,(byte) 0x51,(byte) 0x5c,0x73,(byte) 0xfc,(byte) 0xf9,(byte) 0xf2 };
    // IV 16 bits (préfixe du cipherText)
    byte[] ivBytes = new byte[] { (byte) 0x69,(byte) 0xdd,(byte) 0xa8,(byte) 0x45,(byte) 0x7d,(byte) 0xd4,(byte) 0x25,(byte) 0x4b,(byte) 0xf3,(byte) 0x53,(byte) 0xb7,(byte) 0x73,(byte) 0x30,(byte) 0x4e,(byte) 0xec };
    // Initialisation
    SecretKeySpec key = new SecretKeySpec(keyBytes,"AES");
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    // Mode
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
    String originalText = "hello i am original";
    // ///////////////////////////////ENCRYPTING
    cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);
    byte[] ciphered = cipher.doFinal(originalText.getBytes());
    String cipherText = new String(ciphered,"UTF-8");
    System.out.println("ciphered: " + cipherText);
    // ///////////////////////////////DECRYPTING
    cipher = Cipher.getInstance("AES/CTR/NoPadding");
    cipher.**init(Cipher.DECRYPT_MODE**,ivSpec);
    byte[] plain = **cipher.doFinal(ciphered);**
    originalText = new String(plain,"UTF-8");
    System.out.println("plaintext: " + originalText);
}
I can't figure out what I did wrong Thank you very much for any help This is also the correct way to encrypt some data. This time I tried to encrypt the 4byte City password thanks in advance
////
I made those changes and it worked well, but if I passed, the problem is what cipher Ciphertext. In init() function getByte(). like
byte[] plain = cipher.doFinal(cipherText.getByte("UTF-8"));
'Thank you for your help
Solution
For decryption, you need to be in decrypt_ Initialization password in mode And the conversion from byte [] to string is incorrect (see other answers)
                            The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
                        
                                            
                        THE END
                    
                    
                    
                                                        二维码
                        
                        
                                                
                        