簡體   English   中英

使用相同的密鑰在C#中進行加密並在Java中進行解密

[英]Encrypt in C# and Decrypt in Java with same secret key

我正准備在服務器端(c#)中進行加密,並在android side(Java)中為我的api密鑰解密。 C#中的加密/解密都可以。 而且,在Java中,加密/解密也都可以。 主要問題是C#生成的密文與Java不同,盡管我使用了相同的密鑰。 C#生成的密文無法在Java中解密。 我嘗試如下。

在Java中

 public static String key = "aaaaaaaabbccccbbaaaaaaaabbccccbb";
    private static byte[] key_Array = Base64.decode(key,Base64.DEFAULT);

    public static String encrypt(String plainText)
    {
        try
        {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");

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

            Key secretKey = new SecretKeySpec(key_Array, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);

            return Base64.encodeToString(cipher.doFinal(plainText.getBytes()),Base64.DEFAULT);
        }
        catch (Exception e)
        {
            System.out.println("[Exception]:"+e.getMessage());
        }
        return null;
    }

    public static String decrypt(String encryptedMessage)
    {
        try
        {
            //Cipher _Cipher = Cipher.getInstance("AES");
            //Cipher _Cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            Cipher _Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");

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

            Key SecretKey = new SecretKeySpec(key_Array, "AES");
            _Cipher.init(Cipher.DECRYPT_MODE, SecretKey, ivspec);

            byte decodedMessage[] = Base64.decode(encryptedMessage,Base64.DEFAULT);
            return new String(_Cipher.doFinal(decodedMessage));

        }
        catch (Exception e)
        {
            System.out.println("[Exception]:"+e.getMessage());

        }
        return null;
    }

在C#中

public class Crypt
    {
        // C# Code, CipherMode.CBC
        // CBC version need Initialization vector IV.

        public static string keyStr = "aaaaaaaabbccccbbaaaaaaaabbccccbb";
                                      // FFClY170hLrhsDnKUEhJ4FhVOnrpNNFFClY170hLrhsDnKUE
        public static string Encrypt(string PlainText)
        {
            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(keyStr);
            byte[] KeyArrBytes32Value = new byte[32];
            Array.Copy(keyArr, KeyArrBytes32Value, 24);

            // 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);

        }

        public static string Decrypt(string CipherText)
        {
            RijndaelManaged aes = new RijndaelManaged();
            aes.BlockSize = 128;
            aes.KeySize = 256;

            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            byte[] keyArr = Convert.FromBase64String(keyStr);
            byte[] KeyArrBytes32Value = new byte[32];
            Array.Copy(keyArr, KeyArrBytes32Value, 24);

            // 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 decrypto = aes.CreateDecryptor();

            byte[] encryptedBytes = Convert.FromBase64CharArray(CipherText.ToCharArray(), 0, CipherText.Length);
            byte[] decryptedData = decrypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
            return ASCIIEncoding.UTF8.GetString(decryptedData);
        }
    }

Java輸出

純文本:hla hla

密文:MW6b3AIpNw5RLmhvAro1Yg ==

C#輸出

純文本:hla hla

密文:qsHRHy05GbRv5Q1QNOUlZQ ==

任何想法或替代方式將不勝感激。 謝謝。

問題在於,在Java代碼中,您僅使用192位密鑰,而在C#版本中,您在使用256位密鑰。

您的base64編碼的密鑰是32個字符,轉換為24個字節,只有192位。

這些是Java中令人討厭的行:

public static String key = "aaaaaaaabbccccbbaaaaaaaabbccccbb"; // 32 characters
private static byte[] key_Array = Base64.decode(key, Base64.DEFAULT); // 24 bytes

只需更改Java鍵數組的創建即可解決問題。 就像是:

public static String key = "aaaaaaaabbccccbbaaaaaaaabbccccbb"; // 32 characters
private static byte[] key_Array = new byte[32]; // 32 bytes

static {
    // copy the 24 base64-decoded bytes to the key array
    System.arraycopy(Base64.decode(key, Base64.DEFAULT), 0, key_Array, 0, 24);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM