rc-migration-tests/vb-migration/Strata.Base.Internal/Security/SecurityUtils.vb

69 lines
2.2 KiB
VB.net

Public Class SecurityUtils
#Region " Declarations "
Private Const ENCRYPTION_KEY_SUFFIX As String = "SDT"
Private Const KEY_SIZE_BYTES As Integer = 32 ' 256 bits for AES-256
#End Region
#Region " Methods "
Private Shared Function PadKey(key As String) As String
If key Is Nothing Then
Throw New ArgumentNullException(NameOf(key))
End If
Dim paddedKey As String = key & ENCRYPTION_KEY_SUFFIX
If paddedKey.Length < KEY_SIZE_BYTES Then
paddedKey = paddedKey.PadRight(KEY_SIZE_BYTES, "X"c)
ElseIf paddedKey.Length > KEY_SIZE_BYTES Then
paddedKey = paddedKey.Substring(0, KEY_SIZE_BYTES)
End If
Return paddedKey
End Function
Public Shared Function EncryptValue(value As String, key As String) As String
If value Is Nothing Then
Return Nothing
End If
If String.IsNullOrEmpty(value) Then
Return String.Empty
End If
If key Is Nothing Then
Throw New ArgumentNullException(NameOf(key))
End If
' Create encryptor with default IV
Dim encryption As New EncryptionUtils.SymmetricEncryptor(EncryptionUtils.SymmetricEncryptor.Provider.AES)
Dim result = encryption.Encrypt(New EncryptionUtils.Data(value), New EncryptionUtils.Data(PadKey(key)))
Return result.Base64
End Function
Public Shared Function DecryptValue(encryptedValue As String, key As String) As String
If encryptedValue Is Nothing Then
Return Nothing
End If
If String.IsNullOrEmpty(encryptedValue) Then
Return String.Empty
End If
If key Is Nothing Then
Throw New ArgumentNullException(NameOf(key))
End If
Dim encryption As New EncryptionUtils.SymmetricEncryptor(EncryptionUtils.SymmetricEncryptor.Provider.AES)
' note EncryptValue returns Base64 string so we need to initialized encryptedData as Base64
Dim encryptedData As EncryptionUtils.Data = New EncryptionUtils.Data()
encryptedData.Base64 = encryptedValue
Return encryption.Decrypt(encryptedData, New EncryptionUtils.Data(PadKey(key))).Text
End Function
#End Region
End Class