Monorepo/Encryption/EncryptionLegacy.vb
2021-05-28 10:57:50 +02:00

84 lines
3.1 KiB
VB.net

Imports System.Security.Cryptography
Imports System.Data
Imports System.Data.SqlClient
Public Class EncryptionLegacy
Private TripleDes As New TripleDESCryptoServiceProvider
Private DEFAULT_KEY As String = "!35452didalog="
Private SALT_VALUE As String = "!Didalog35452Heuchelheim="
Sub New()
TripleDes.Key = TruncateHash(DEFAULT_KEY, TripleDes.KeySize \ 8)
TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8)
End Sub
Sub New(ByVal key As String)
' Initialize the crypto provider.
TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8)
TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8)
End Sub
Private Function TruncateHash(ByVal key As String, ByVal length As Integer) As Byte()
Dim sha1 As New SHA1CryptoServiceProvider
' Hash the key.
Dim keyBytes() As Byte =
System.Text.Encoding.Unicode.GetBytes(key)
Dim hash() As Byte = sha1.ComputeHash(keyBytes)
' Truncate or pad the hash.
ReDim Preserve hash(length - 1)
Return hash
End Function
Public Function EncryptData(ByVal plaintext As String) As String
Try
' Convert the plaintext string to a byte array.
Dim plaintextBytes() As Byte =
System.Text.Encoding.Unicode.GetBytes(SALT_VALUE & plaintext)
' Create the stream.
Dim ms As New System.IO.MemoryStream
' Create the encoder to write to the stream.
Dim encStream As New CryptoStream(ms,
TripleDes.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()
' Convert the encrypted stream to a printable string.
Return Convert.ToBase64String(ms.ToArray)
Catch ex As Exception
Return plaintext
End Try
End Function
'Entschlüsselt die Zeichenfolge
Public Function DecryptData(ByVal EncryptedText As String) As String
Try
' Convert the encrypted text string to a byte array.
Dim oEncryptedBytes() As Byte = Convert.FromBase64String(EncryptedText)
' Create the stream.
Dim oMemoryStream As New System.IO.MemoryStream
' Create the decoder to write to the stream.
Dim oCryptoStream As New CryptoStream(oMemoryStream,
TripleDes.CreateDecryptor(),
System.Security.Cryptography.CryptoStreamMode.Write)
' Use the crypto stream to write the byte array to the stream.
oCryptoStream.Write(oEncryptedBytes, 0, oEncryptedBytes.Length)
oCryptoStream.FlushFinalBlock()
Dim oResult = System.Text.Encoding.Unicode.GetString(oMemoryStream.ToArray)
oResult = oResult.Replace(SALT_VALUE, "")
' Convert the plaintext stream to a string.
Return oResult
Catch ex As Exception
Return EncryptedText
End Try
End Function
End Class