samedi 25 juin 2016

.Net Encrypt XML stream with AES and 128 bit Initialization vector

I am working on a project where I am posting to a web service via XML stream. In this case the provider is requesting that the routing xml be encrypted with Advanced Encryption Standard (AES) in Cipher Block Chaining (CBC) mode with a 128 bit initialization vector. I am coding in VB.Net and from what I can tell I have met all of their encryption requirements, but I keep getting an "Invalid Routing Input encryption" error response when I submit the post. I have not done much with encryption so I was hoping that someone with some encryption experience could help me out here. Is it failing because I am not prefixing the IV correctly? Is there a standard way in AES to merge IV to the cipher data? Or is there a problem with how I am doing the encryption itself? I’ve been stuck here for awhile and tried a couple different ways of encrypting but have not had success. Listed below is my code and a summary of the encryption requirements.

  1. Generate a symmetric key using Advanced Encryption Standard (AES) in Cipher Block Chaining (CBC) mode with a 128 bit initialization vector [AES] algorithm. Do not use a zero byte initialization vector.

  2. Encrypt the valid Routing Input xml document using the AES symmetric key. Prefix the resulting cipher text with the 128 bit initialization vector. (It is not recommended to use an initialization vector with all 0 bytes.)

  3. Base64 encode the initialization vector and the encrypted Routing Input xml document.

  4. Build the ENCRYPTED_RI xml element using the base64 encoded initialization vector and encrypted Routing Input xml document.

  5. Generate SHA1 hash for the plaintext Routing Input xml document.

  6. Concatenate the SHA1 hash of the plaintext Routing Input xml document and AES symmetric key. (SHA1 hash + AES symmetric key)

  7. Encrypt the concatenated result using the public key and RSA version 1.5 algorithm [RFC 2437].

  8. Base64 encode the encrypted concatenated result.

  9. Build the ENCRYPTED_KEY xml element using the base64 encoded encrypted concatenated result.

Here is my code:

Sub CreateEncryptionXML()
    '############
    '## CREATE AES KEY AND IV
    '############
    Dim SymKey() As Byte
    Dim IV() As Byte
    Dim aes As New AesCryptoServiceProvider

    Using myAes As Aes = System.Security.Cryptography.Aes.Create()
        myAes.KeySize = 128
        myAes.BlockSize = 128
        myAes.Mode = CipherMode.CBC
        myAes.Key = Encoding.UTF8.GetBytes("MyEncryptionKey1")
        myAes.IV = Encoding.UTF8.GetBytes("MyInitialVector1")

        SymKey = myAes.Key
        IV = myAes.IV
    End Using

    '############
    '## ENCRYPT ROUTING INPUT XML DOC
    '############
    Dim riXml As New XmlDocument
    riXml.Load("C:routingdoc.xml")        
    aes.Key = SymKey
    aes.IV = IV
    aes.Mode = CipherMode.CBC

    ' Convert the plaintext string to a byte array.
    Dim plaintextBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(riXml.OuterXml.ToString())

    ' Create the stream.
    Dim ms As New System.IO.MemoryStream

    ' Create the encoder to write to the stream.
    Dim encStream As New CryptoStream(ms, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)

    ' Use the crypto stream to write the byte array to the stream.
    encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
    encStream.FlushFinalBlock()


    '############
    '## PREFIX CIPHER TEXT WITH IV
    '############
    Dim encRiXml() As Byte = ms.ToArray
    Dim arraySize As Integer = IV.Length + encRiXml.Length
    Dim Merged(arraySize) As Byte
    IV.CopyTo(Merged, 0)
    encRiXml.CopyTo(Merged, IV.Length)

    Dim Base64IVEncRiXML As String = Convert.ToBase64String(Merged)

    '******** I BELIVE EVERYTHING PAST HERE IS CORRECT BUT INCLUDED IT TO SHOW WHOLE PROCESS **********

    '############
    '## CREATE SHA1 HASH FOR PLAINTEXT ROUTING INPUT
    '############
    Dim hash() As Byte = New SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(riXml.OuterXml.ToString()))

    '############
    '## CONCATENATE THE SHA1 HASH OF PLAINTEXT ROUTING INPUT XML WITH AES KEY
    '############
    Dim arraySize2 As Integer = hash.Length + SymKey.Length
    Dim Merged2(arraySize2) As Byte
    hash.CopyTo(Merged2, 0)
    SymKey.CopyTo(Merged2, hash.Length)

    '############
    '## ENCRYPT CONCATENATED RESULT USING RSA
    '############
    Dim EncryptionKey As String = File.ReadAllText("C:cert-1.txt").Replace("-----BEGIN CERTIFICATE-----" & vbCr & vbLf, "").Replace("-----END CERTIFICATE-----", "")

    TextBox1.Text = EncryptionKey

    Dim binaryCertData() As Byte = Convert.FromBase64String(EncryptionKey)
    Dim cert As X509Certificate2 = New X509Certificate2(binaryCertData)
    Dim xmlKey As String = cert.PublicKey.Key.ToXmlString(False)
    Dim objRSA As RSACryptoServiceProvider = New RSACryptoServiceProvider()
    objRSA.FromXmlString(xmlKey)

    Dim encrypted() As Byte = objRSA.Encrypt(Merged2, False)

    Dim RSAEncryptedSHA1HashAESKey As String = Convert.ToBase64String(encrypted)

    postStaticTest(RSAEncryptedSHA1HashAESKey, Base64IVEncRiXML)
End Sub

'PROVIDED SAMPLE OF XML OUTPUT FROM DOCUMENTATION
'<?xml version="1.0" encoding="UTF-8"?>
'<SECURE_REQUEST_GROUP>
'<ENCRYPTED_KEY Algorithm=”http://www.w3.org/2001/04/xmlenc#rsa-1_5” >
'bXcCaS97p8TtGzlgZ9ogRcEAaw1D1OQCpk1AQFfWYE5J2CheNtRBpuME+uB3wSkwjIWftkYxQ5JRTQ3Qhz7LrCM+TOORl2lFFTpVC9zGUP1xndfT6EQONViV0XGJieWCzXNyjO3XpEl7IdntkVKucrDN9gA7wlimUdw4Ya5sn08=
'</ ENCRYPTED_KEY>
'< ENCRYPTED_RI Algorithm=”http://www.w3.org/2001/04/xmlenc#aes128-cbc”>
'9BWPkFDt0Ua/2gN9+BDT9XbYHBuadEREIV1EUmvon/jSr0HkndD/9lBo95H3UYD12TL3wmXVSqi7Ak/QqxzmVRDMgw2Wy0Ezdc3eaA9tOE1c49ZcaZpGM23R1BOazTGdky5v2+oBvSj4a+Ry/aJynvzKvxpTYd15IKOOzPsF/n89Oj6XdjA1TTdn2FCEwo6IkPi0D5QK2i1i/pilEyrrSYQ0oWkYc6ON/OQyL/oHlkBXk0zzQd1HBPOde4/3C6ceajUTvqiIlP6dRBHe6DZ3Ps34g7326jg3koh59RYao/0StgpF3wTJaZ/W36nqlpT3aeoLa/5oKh4A7DjHbYCHTw1uYkPXVGLFl6zTpFRw8hGkPfBRZmS5lXnQl6xidqftb+fx61yBj80/FHAlvmUzBsSQZggeXzBjqlVoWudCuGdC5QH1xKBWrm8haS2UIEdK/DH8fC13oFMpS++C7HTc/u9N8iH6qF0GimxYHvhKwdk3iw/hxrw5Bv1/tQjI1snJm9U1HnokDwG5BWZJp8jBuPgJIapc/DQgIEbM+3NMJXoB/ed9PquPFPPlfoo4E13a3PZPYIDImnLkOjvdPMrZ8A==
'</ ENCRYPTED_RI>
'</SECURE_REQUEST_GROUP>

Aucun commentaire:

Enregistrer un commentaire