Ошибка Sage Pay 3045: отсутствует поле «Валюта». НЕПРАВИЛЬНЫЙ

Я пытаюсь обновить версию Sage Pay с 2.22 до 3.00 и использую Form Intergration для отправки значений в Sage. Коды написаны asp.net(VB). В версии 2.2 использовался «алгоритм шифрования SimpleXor», но это не разрешено в версии 3.00, и в результате я получаю следующее сообщение об ошибке:

Эта попытка транзакции не удалась. Мы не можем перенаправить вас обратно в интернет-магазин, в котором вы совершали покупку. Подробности неисправности приведены ниже.

Status: INVALID
Status Detail: 5068 : The encryption method is not supported by this protocol version.

Я обнаружил, что версия 3.00 допускает только шифрование AES, и я добавил приведенный ниже код в файл класса для шифрования:

Public Shared Function AESEncrypt(ByVal clearText As String) As String
        Dim EncryptionKey As String = "MAKV2SPBNI99212"
        Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText)
        Using encryptor As Aes = Aes.Create()
            Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _
             &H65, &H64, &H76, &H65, &H64, &H65, _
             &H76})
            encryptor.Key = pdb.GetBytes(32)
            encryptor.IV = pdb.GetBytes(16)
            Using ms As New MemoryStream()
                Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)
                    cs.Write(clearBytes, 0, clearBytes.Length)
                    cs.Close()
                End Using
                clearText = Convert.ToBase64String(ms.ToArray())
            End Using
        End Using
        Return clearText
    End Function

И в основном файле .vb я меняю следующий код:

Dim strXOR As String = simpleXor(strPost, strEncryptionPassword)
strCrypt = base64Encode(strXOR)

To

Dim aesEncrypt As String = AESEncrypt(strPost)
strCrypt = "@" & aesEncrypt

Извините, я начинаю в этом. Есть ли какие-либо ошибки, которые я сделал в своем файле класса или в основном файле vb? Нужно ли кодировать base64 после шифрования AES?

Заранее спасибо.


person Mahesh    schedule 22.07.2015    source источник


Ответы (1)


ХОРОШО. Соревнуйтесь, перепишите ответ.

Выкиньте код, который у вас есть - я нашел его на другом сайте, и он не будет работать.

Вместо этого используйте приведенный ниже материал (который я немного адаптировал из здесь):

 Public Shared Function AESEncryption(ByVal strCrypt As String, ByVal strEncryptionPassword As String) As String

        Dim keyAndIvBytes As Byte() = UTF8Encoding.UTF8.GetBytes(strEncryptionPassword)

        Using AES As New RijndaelManaged()
            ' Set the mode, padding and block size for the key
            AES.Padding = PaddingMode.PKCS7
            AES.Mode = CipherMode.CBC
            AES.KeySize = 128
            AES.BlockSize = 128

            ' Encrypt the string to an array of bytes. 
            Dim encrypted As Byte() = EncryptStringToBytes(strCrypt, keyAndIvBytes, keyAndIvBytes)

            AESEncryption = "@" & BitConverter.ToString(encrypted).Replace("-", "").ToUpper
            ' System.Console.WriteLine(AESEncryption)
        End Using
    End Function

    Public Shared Function AESDecryption(ByVal strCrypt As String, ByVal strEncryptionPassword As String) As String

        Dim keyAndIvBytes As [Byte]() = UTF8Encoding.UTF8.GetBytes(strEncryptionPassword)

        ' Create a new instance of the RijndaelManaged 
        ' class.  This generates a new key and initialization  
        ' vector (IV). 
        Using AES As New RijndaelManaged()
            ' Set the mode, padding and block size for the key
            AES.Padding = PaddingMode.PKCS7
            AES.Mode = CipherMode.CBC
            AES.KeySize = 128
            AES.BlockSize = 128

            Dim encryptedData As Byte() = StringToByteArray(strCrypt.Remove(0, 1))

            Dim roundtrip As String = DecryptStringFromBytes(encryptedData, keyAndIvBytes, keyAndIvBytes)

            AESDecryption = roundtrip
        End Using
    End Function
    Shared Function byteArrayToHexString(ByVal ba As Byte()) As String
        Return BitConverter.ToString(ba).Replace("-", "")
    End Function
    Shared Function StringToByteArray(ByVal hex As String) As Byte()
        Return Enumerable.Range(0, hex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(hex.Substring(x, 2), 16)).ToArray()
    End Function

    Shared Function EncryptStringToBytes(ByVal plainText As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
        ' Check arguments. 
        If plainText Is Nothing OrElse plainText.Length <= 0 Then
            Throw New ArgumentNullException("plainText")
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException("IV")
        End If
        Dim encrypted() As Byte
        ' Create an RijndaelManaged object 
        ' with the specified key and IV. 
        Using AES As New RijndaelManaged()
            AES.Padding = PaddingMode.PKCS7
            AES.Mode = CipherMode.CBC
            AES.KeySize = 128
            AES.BlockSize = 128

            AES.Key = Key
            AES.IV = IV

            ' Create a decrytor to perform the stream transform. 
            Dim encryptor As ICryptoTransform = AES.CreateEncryptor(AES.Key, AES.IV)
            ' Create the streams used for encryption. 
            Using msEncrypt As New MemoryStream()
                Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
                    Using swEncrypt As New StreamWriter(csEncrypt)

                        'Write all data to the stream.
                        swEncrypt.Write(plainText)
                    End Using
                    encrypted = msEncrypt.ToArray()
                End Using
            End Using
        End Using

        ' Return the encrypted bytes from the memory stream. 
        Return encrypted

    End Function 'EncryptStringToBytes

    Shared Function DecryptStringFromBytes(ByVal cipherText() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String

        ' Check arguments. 
        If cipherText Is Nothing OrElse cipherText.Length <= 0 Then
            Throw New ArgumentNullException("cipherText")
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException("IV")
        End If
        ' Declare the string used to hold 
        ' the decrypted text. 
        Dim plaintext As String = Nothing

        ' Create an RijndaelManaged object 
        ' with the specified key and IV. 
        Using AES As New RijndaelManaged
            AES.Padding = PaddingMode.PKCS7
            AES.Mode = CipherMode.CBC
            AES.KeySize = 128
            AES.BlockSize = 128

            'AES.Key = Key
            'AES.IV = IV

            ' Create a decrytor to perform the stream transform. 
            Dim decryptor As ICryptoTransform = AES.CreateDecryptor(Key, IV)

            ' Create the streams used for decryption. 
            Using msDecrypt As New MemoryStream(cipherText)

                Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)

                    Using srDecrypt As New StreamReader(csDecrypt)


                        ' Read the decrypted bytes from the decrypting stream 
                        ' and place them in a string.
                        plaintext = srDecrypt.ReadToEnd()
                    End Using
                End Using
            End Using
        End Using

        Return plaintext

    End Function

И в вашем файле main.vb измените:

Dim strXOR As String = simpleXor(strPost, strEncryptionPassword)
strCrypt = base64Encode(strXOR)

To:

strCrypt=AESEncryption(strPost, strEncryptionPassword)
person Rik Blacow    schedule 22.07.2015
comment
Привет.. Спасибо за ответ.. Но если я удалил строку clearText = Convert.ToBase64String(ms.ToArray()) в clearText = Encoding.ASCII.GetString(ms.ToArray()) из функции, но это не работает . Я также изменил ключ доступа. - person Mahesh; 22.07.2015