1

Bouncy Castle CRT Csharp, Decrypt failed to get the plain text

Test failed

   static void Main(string[] args) {
        string toEncrypt = "This is a test string";
        byte[] key = Encoding.ASCII.GetBytes("0123456789abcdef");            
        byte[] iv = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };

        Console.Write("\n Plain: " + toEncrypt); 

        // create AES cipher
        IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CTR/NoPadding");
        cipher.Init(true, new ParametersWithIV(ParameterUtilities.CreateKeyParameter("AES", key), iv));

        // encrypted
        byte[] input = Encoding.ASCII.GetBytes(toEncrypt);
        byte[] encryptedBytes = cipher.DoFinal(input);
        string base64EncryptedOutputString = Convert.ToBase64String(encryptedBytes);
        Console.Write("\n Base64Encrypted:" + base64EncryptedOutputString);

        // decrypted
        byte[] toDecrypt = Encoding.ASCII.GetBytes(base64EncryptedOutputString);
        cipher.Init(false, new ParametersWithIV(ParameterUtilities.CreateKeyParameter("AES", key), iv));
        byte[] plainBytes = cipher.DoFinal(toDecrypt);
        Console.WriteLine("\n Decrypted:" + Encoding.ASCII.GetString(plainBytes));
    }

Plain: This is a test string

Base64Encrypted:71WVSPK31A+QrCUyqppI56fQixMV

Decrypted:??m?????z??=????4G???e?w?

---> Decrypted not the same with PLAIN Text :)

  • You shouldn’t use ASCII as it only supports 128 basic Latin letters, numbers, and symbols. Use UTF8 instead to support all 100,000+ Unicode characters. – ckuri Jun 16 '19 at 12:28

1 Answers1

2

The problem is that you're missing the conversion from base64 back to the original byte array.

Instead of:

byte[] toDecrypt = Encoding.ASCII.GetBytes(base64EncryptedOutputString);

You need:

byte[] toDecrypt = Convert.FromBase64String(base64EncryptedOutputString);

See MSDN

haim770
  • 48,394
  • 7
  • 105
  • 133