Cross-platform encryption/decryption - Handling Keys and Initialization Vectors (IV)
After looking through a number of examples I have peiced together some encryption/decryption methods that make use of Rfc2898DeriveBytes
to obtain the key and initialization vector. My concern is that the party receiving my encrypted content must be able to decrypt i开发者_开发技巧t. Since I have no control over what language they are using (could be Java, PHP, C, etc ..) how do I ensure that they are able to derive the Key and Initialization Vector (IV) as I have using the Rfc2898DeriveBytes
class in .NET? Here are the encryption and decryption methods I am using.
Public Shared Function EncryptText(ByVal plainText As String, ByVal password As String) As String
Dim aesCrypto As Rijndael = Nothing
Dim plainTextBytes As Byte()
plainTextBytes = Encoding.Default.GetBytes(plainText)
Dim rfc2898 As Rfc2898DeriveBytes
rfc2898 = New Rfc2898DeriveBytes(password, GenerateSalt(password))
aesCrypto = Rijndael.Create()
aesCrypto.Padding = PaddingMode.ISO10126
Dim tx As ICryptoTransform
tx = aesCrypto.CreateEncryptor(rfc2898.GetBytes(32), rfc2898.GetBytes(16))
Dim encryptedBytes As Byte()
encryptedBytes = tx.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length)
Return Convert.ToBase64String(encryptedBytes)
End Function
Public Shared Function DecryptText(ByVal encryptedText As String, ByVal password As String) As String
Dim aesCrypto As Rijndael = Nothing
Dim encryptedTextBytes As Byte()
encryptedTextBytes = Convert.FromBase64String(encryptedText)
Dim rfc2898 As Rfc2898DeriveBytes
rfc2898 = New Rfc2898DeriveBytes(password, GenerateSalt(password))
aesCrypto = Rijndael.Create()
aesCrypto.Padding = PaddingMode.ISO10126
Dim tx As ICryptoTransform
tx = aesCrypto.CreateEncryptor(rfc2898.GetBytes(32), rfc2898.GetBytes(16))
Dim decryptedBytes As Byte()
decryptedBytes = tx.TransformFinalBlock(encryptedTextBytes, 0, encryptedTextBytes.Length)
Return Encoding.Default.GetString(decryptedBytes)
End Function
You would tell the recipient to implement PBKDF2, which is a standard defined in RFC2898 and PKCS #5. Microsoft's documentation says that their function uses HMAC-SHA-1 as the pseudorandom function, and 1000 as the default number of iterations. This is the information they'll need.
However, you will also need to transmit the salt that was created with GenerateSalt()
on the sending side. The recipient cannot just call GenerateSalt()
themselves - it should be randomly generated for each message.
精彩评论