簡體   English   中英

將.NET AES加密轉換為Java

[英]Converting .NET AES encryption to Java

我正在嘗試編寫等效於某些.NET加密代碼的Java,以便它們可以通過Web服務解密我們的信息。

這是.NET方法:

public static string AESEncrypt(string text, string keyPhrase)
    {
        byte[] salt = { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 };
        byte[] data = Encoding.Unicode.GetBytes(text);
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(keyPhrase, salt);

        Rijndael algorithm = Rijndael.Create();
        algorithm.Key = pdb.GetBytes(32);
        algorithm.IV = pdb.GetBytes(16);

        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
        cStream.Write(data, 0, data.Length);
        cStream.Close();
        byte[] bytes = mStream.ToArray();

        return Convert.ToBase64String(bytes);
    }

這是我在Java版本上失敗的嘗試:

public static String encrypt(String text, String keyPhrase) throws Exception {
        byte[] salt = { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 };
        byte[] data = text.getBytes("UTF-16LE");
        PBEKeySpec spec = new PBEKeySpec(keyPhrase.toCharArray(), salt, 1);

        SecretKey secret = new SecretKeySpec(keyPhrase.getBytes("UTF-16LE"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, secret);
        byte[] ciphertext = cipher.doFinal(data);
        return Base64.encodeBase64String(ciphertext);
    }

我遇到的第一個問題是弄清楚如何將KeyD和iv的PasswordDeriveBytes進行匹配,盡管我確信其余的都是錯誤的,但是要小心。 有誰知道如何匹配Java版本中的輸出?

要在Java中匹配PasswordDeriveBytes,請使用此stackoverflow答案中的PasswordDeriveBytes(擴展org.bouncycastle.crypto.generators.PKCS5S1ParametersGenerator)。

但這僅適用於20字節以下的密鑰! 這是生成密鑰的代碼:

String text="marcoS";
String keyPhrase="password123";
byte[] salt={ 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 };

PasswordDeriveBytes generator = new PasswordDeriveBytes(new SHA1Digest());
generator.init(keyPhrase.getBytes("ASCII"), salt, 100);
byte[] key = ((KeyParameter) generator.generateDerivedParameters(KeySize)).getKey();    

或者在dotNet中用Rfc2898DeriveBytes替換PasswordDeriveBytes。

要打印無符號字節(與.net匹配),請使用:

private static void printByteArray(byte[] arr) {
    if(arr == null || arr.length == 0){
        logger.debug("Array vuoto");
        return;
    }
    StringBuilder sb = new StringBuilder();
    for(byte b : arr)   {
        int x = b;
        if(x<0){
            x+=256;
        }
        sb.append("["+x+"] ");
    }
    logger.debug(sb.toString());
}

暫無
暫無

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

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