簡體   English   中英

Java 256 位 AES 加密

[英]Java 256-bit AES Encryption

我需要為現金流實現 256 位 AES 加密我有 c# 答案,但答案不一樣,對於新手,我不確定我的方向是否正確。

這是我的代碼

public static void main(String[] args) {
            String key = "12345678901234567890123456789012";
            String hashIv = "1234567890123456";
            String value = "MerchantID=3430112RespondType=JSONTimeStamp=1485232229Version=1.4MerchantOrderNo=S_1485232229Amt=40ItemDesc=UnitTest";
            String result = encrypt(key, hashIv, value);
            System.out.println(result);
            System.out.println();

            String sha256 = encrySha256("HashKey=" + key + "&" + result + "&HashIV=" + hashIv);
            System.out.println(sha256.trim());
        }

    public static String encrypt(String hashKey, String hashIv, String text) {

            try {
                SecretKeySpec skeySpec = new SecretKeySpec(hashKey.getBytes("UTF-8"), "AES");
                IvParameterSpec ivParameterSpec = new IvParameterSpec(hashIv.getBytes("UTF-8"));
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
                byte[] encrypted = cipher.doFinal((text.getBytes("UTF-8")));
                String test = bytesToHex(encrypted);

                return test.toLowerCase();          
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            return null;
        }

        public static String bytesToHex(byte[] bytes) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < bytes.length; i++) {
                String hex = Integer.toHexString(bytes[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();

        }

public static String encrySha256(String value) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(value.getBytes());
            byte byteBuffer[] = messageDigest.digest();
            StringBuffer strHexString = new StringBuffer();

            for (int i = 0; i < byteBuffer.length; i++) {
                String hex = Integer.toHexString(0xff & byteBuffer[i]);
                if (hex.length() == 1) {
                    strHexString.append('0');
                }
                strHexString.append(hex);
            }
            return strHexString.toString().toUpperCase();
        } catch (Exception e) {

        }
        return null;
    }

示例加密答案:

ff91c8aa01379e4de621a44e5f11f72e4d25bdb1a18242db6cef9ef07d80b0165e476fd1d
9acaa53170272c82d122961e1a0700a7427cfa1cf90db7f6d6593bbc93102a4d4b9b66d9
974c13c31a7ab4bba1d4e0790f0cbbbd7ad64c6d3c8012a601ceaa808bff70f94a8efa5a4f
984b9d41304ffd879612177c622f75f4214fa

encryptSha256 答案: EA0A6CC37F40C1EA5692E7CBB8AE097653DF3E91365E6A9CD7E91312413C7BB8

這是 C# 代碼,這是示例數據

[MerchantID] => 3430112 [RespondType] => JSON [TimeStamp] => 1485232229 [Version] => 1.4 [MerchantOrderNo] => S_1485232229 [Amt] => 40 [ItemDesc] => UnitTest

    public string EncryptAES256(string source)//加密
    {
    string sSecretKey = "12345678901234567890123456789012";
    string iv = "1234567890123456";
    byte[] sourceBytes =
    AddPKCS7Padding(Encoding.UTF8.GetBytes(source), 32);
    var aes = new RijndaelManaged();
    aes.Key = Encoding.UTF8.GetBytes(sSecretKey);
    aes.IV = Encoding.UTF8.GetBytes(iv);
    aes.Mode = CipherMode.CBC;
    aes.Padding = PaddingMode.None;
    ICryptoTransform transform = aes.CreateEncryptor();
    return ByteArrayToHex(transform.TransformFinalBlock(sourceBytes, 0,
    sourceBytes.Length)).ToLower();
    }

    private static byte[] AddPKCS7Padding(byte[] data, int iBlockSize)
    {
    int iLength = data.Length;
    byte cPadding = (byte)(iBlockSize - (iLength % iBlockSize));
    var output = new byte[iLength + cPadding];
    Buffer.BlockCopy(data, 0, output, 0, iLength);
    for (var i = iLength; i < output.Length; i++)
    output[i] = (byte)cPadding;
    return output;
    }

    private static string ByteArrayToHex(byte[] barray)
    {
    char[] c = new char[barray.Length * 2];
    byte b;
    for (int i = 0; i < barray.Length; ++i)
    {
    b = ((byte)(barray[i] >> 4));
    c[i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30);
    b = ((byte)(barray[i] & 0xF));
    c[i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);
    }
    return new string(c);
    }

不同加密數據的原因是您比較了不同的純文本 在您的 Java 代碼中,您加密純文本

  MerchantID=3430112RespondType=JSONTimeStamp=1485232229Version=1.4MerchantOrderNo=S_1485232229Amt=40ItemDesc=UnitTest

並將加密數據與參考數據進行比較

  ff91c8aa01379e4de621a44e5f11f72e4d25bdb1a18242db6cef9ef07d80b0165e476fd1d9acaa53170272c82d122961e1a0700a7427cfa1cf90db7f6d6593bbc93102a4d4b9b66d9974c13c31a7ab4bba1d4e0790f0cbbbd7ad64c6d3c8012a601ceaa808bff70f94a8efa5a4f984b9d41304ffd879612177c622f75f4214fa

但是,這些參考數據對應的是不同的純文本 后者您可以通過使用 C# DecryptAES256 方法解密參考數據來輕松推導,該方法提供

  MerchantID=3430112&RespondType=JSON&TimeStamp=1485232229&Version=1.4&MerchantOrderNo=S_1485232229&Amt=40&ItemDesc=UnitTest

與 Java 代碼中的純文本相比,這里使用了& -delimiter。

如果您使用相同的純文本,Java encrypt- 和 C# EncryptAES256-method 提供相同的加密數據(相同的密鑰、IV 和填充假設;后者參見編輯部分)。

在以下測試用例中,使用了 Java 代碼中的純文本:

 encrypt("12345678901234567890123456789012", "1234567890123456", "MerchantID=3430112RespondType=JSONTimeStamp=1485232229Version=1.4MerchantOrderNo=S_1485232229Amt=40ItemDesc=UnitTest")

 EncryptAES256("MerchantID=3430112RespondType=JSONTimeStamp=1485232229Version=1.4MerchantOrderNo=S_1485232229Amt=40ItemDesc=UnitTest")

兩者都提供加密數據:

 ff91c8aa01379e4de621a44e5f11f72ef45b7b9f9663d386da51af13f7f3b8f2b1ed4a3b7ac6b7783402193ea1d766e3046b6acf612d62568ccdbc475e5a14d114273735b069464dcc8281f4e5bf8486eb97d31602c3fe79cfe7140d2848413edad9d96fabf54d103f3d7a9b401c83fa5e4f17b10a280df10b3d61f23e69bbb8

這(如預期)與您的參考數據不同(第一個塊除外)。

編輯

關於填充還有第二個問題:您的 C# EncryptAES256 方法使用由 C# AddPKCS7Padding-method 提供的自定義填充,該方法填充為32 bytes的倍數。

相比之下,您的 Java 加密方法使用 PKCS5Padding 填充到16 bytes的倍數。

因此,如果純文本的長度在 16 * n 字節和 16 * (n + 1) - 1 字節之間,甚至 n (0,2,4 ,...)。

對於奇數 n (1,3,5,...),加密數據是相同的。 在上面的示例中,純文本的字節數組有 116 個字節,即 n = 7 (112 <= 116 <= 127),因此加密數據是相同的。

如果 Java 加密方法應使用與 C# EncryptAES256 方法相同的填充,則您還必須實現類似的 Java 方法,例如:

private static byte[] addPKCS7Padding(byte[] data, int iBlockSize)
{
    int iLength = data.length;
    byte cPadding = (byte)(iBlockSize - (iLength % iBlockSize));
    byte[] output = new byte[iLength + cPadding];
    System.arraycopy(data, 0, output, 0, iLength);
    for (int i = iLength; i < output.length; i++)
        output[i] = (byte)cPadding;
    return output;
}

在 Java 加密方法中,您必須替換:

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

 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

並且

 byte[] encrypted = cipher.doFinal(text.getBytes("UTF-8"));

 byte[] encrypted = cipher.doFinal(addPKCS7Padding(text.getBytes("UTF-8"), 32));

前:

MerchantID=3430112RespondType=JSONTimeStamp=1485232229Version=1.4MerchantOrderNo=S_1485232229Amt=40ItemDesc=UnitTest

后:

MerchantID=3430112&RespondType=JSON&TimeStamp=1485232229&Version=1.4&MerchantOrderNo=S_1485232229&Amt=40&ItemDesc=UnitTest

我只為每個參數添加“&”,它的工作!!!! 嘗試一下!!!

(我只加了&就成功拉,你的代碼沒問題,只有參數要加&就成功了)

暫無
暫無

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

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