Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
A scenario like API developed in Java and have to consume in asp.net C#. The problem is with encryption and decryption of payload. Algorithm AES-256 , the generated encrypted text in c# is not matching with Java. Kindly help. Thanks in Advance.

What I have tried:

JAVA CODE : 
public static void main(String args[]) 
    {
        MyClass obj = new MyClass();

        String mdString = obj.generateAESEncryption("dfgfrhdfgfrhdfgfrhdfgfrhdfgfrhil", "1");

        System.out.println(" AES 256 Encrypted Key : " + mdString);
    }

    public String generateAESEncryption(String sercretKey, String message) 
    {

        String base64EncryptedString = "";

        MessageDigest md = null;
        try {

            md = MessageDigest.getInstance("SHA-256");


            byte[] digestOfPassword = md.digest(sercretKey.getBytes(StandardCharsets.UTF_8));
            
            System.out.println(" Message Digest Byte[] String : " + digestOfPassword);
            

            byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

            byte[] iv = Arrays.copyOf(digestOfPassword, 16);
            
            System.out.println(" keyBytes Byte[] String : " + digestOfPassword);
            System.out.println(" iv Byte[] String : " + digestOfPassword);

            SecretKey key = new SecretKeySpec(keyBytes, "AES");

            Cipher cipher = null;
            try {
                    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");


                    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

                    try 
                    {
                        cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
                    } 
                    catch (InvalidAlgorithmParameterException | InvalidKeyException e) 
                    {
                        e.printStackTrace();
                    }

                    byte[] plainTextBytes = message.getBytes(StandardCharsets.UTF_8);
                    
                    System.out.println(" plainTextBytes Byte[] String : " + digestOfPassword);

                    byte[] buf = new byte[0];
                    try 
                    {
                        buf = cipher.doFinal(plainTextBytes);
                    } 
                    catch (BadPaddingException e) 
                    {
                        e.printStackTrace();
                    } 
                    catch (IllegalBlockSizeException e) 
                    {
                        e.printStackTrace();
                    }

                    //byte[] encryptedByteValue = new Base64().encode(buf);
                    byte[] encryptedByteValue = Base64.getEncoder().encode(buf);

                    //String encryptedValue = encryptedByteValue.toString();
                    base64EncryptedString = new String(encryptedByteValue, StandardCharsets.UTF_8);

                    //Logger.debug("AES : ", "EncryptedValue : " + base64EncryptedString);

                } 
                catch (NoSuchPaddingException e) 
                {
                    e.printStackTrace();
                }
        } 
        catch (NoSuchAlgorithmException e) 
        {
            e.printStackTrace();
        }

        return base64EncryptedString;
    }
}

C# Code : 

        private static string Encrypt_2(string PlainText, String key)
        {
            HashAlgorithm Hasher = new SHA256CryptoServiceProvider();
            byte[] strBytes = Encoding.UTF8.GetBytes(key);
            byte[] passBytes = Hasher.ComputeHash(strBytes);

            RijndaelManaged aes = new RijndaelManaged();
            aes.BlockSize = 128;
            aes.KeySize = 256;

            // It is equal in java 
            /// Cipher _Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");    
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            byte[] keyArr = Convert.FromBase64String(key);
            byte[] KeyArrBytes32Value = new byte[24];
            Array.Copy(passBytes, KeyArrBytes32Value, 16);

            // Initialization vector.   
            // It could be any value or generated using a random number generator.
            byte[] ivArr = { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1, 7, 7, 7, 7 };
            byte[] IVBytes16Value = new byte[16];
            Array.Copy(ivArr, IVBytes16Value, 16);

            aes.Key = KeyArrBytes32Value;
            aes.IV = IVBytes16Value;

            ICryptoTransform encrypto = aes.CreateEncryptor();

            byte[] plainTextByte = ASCIIEncoding.UTF8.GetBytes(PlainText);
            byte[] CipherText = encrypto.TransformFinalBlock(plainTextByte, 0, plainTextByte.Length);
            return Convert.ToBase64String(CipherText);

        }
Posted
Updated 11-Sep-20 18:00pm
v2
Comments
OriginalGriff 11-Sep-20 16:51pm    
We are more than willing to help those that are stuck: but that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you.

So we need you to do the work, and we will help you when you get stuck. That doesn't mean we will give you a step by step solution you can hand in!
Start by explaining where you are at the moment, and what the next step in the process is. Then tell us what you have tried to get that next step working, and what happened when you did.
BillWoodruff 12-Sep-20 3:21am    
"generated encrypted text in c# is not matching with Java" why are you mixing C# and Java ?

1 solution

You need to ensure things like the IV and Padding (and obviously, cypher, cypher mode) are the same ...

In your case, for instance, in the java I dont know what IV is generated, and you're using PKCS5 padding .. in C#, you set an IV, and use PKCS7 padding

I don't have time to pull your code apart, so I'll supply you with 2 URL's where people 'say' (I havent tested) that they have it correct, maybe you'll be able to cross check or just use their code, with attribution of course)

Michael Remijan: AES Encryption between Java and C#[^]

(interestingly, that one uses PCKs5 padding in Java and PKCS7 padding in C#, but note the IV's are the same)

AES-128 (Compatability C# & Java) · GitHub[^]
 
Share this answer
 
Comments
BillWoodruff 12-Sep-20 3:19am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900