Encryption and Decryption in VB.NET
We have to store some data securely, the best method is , convert the values into encryption and then store into database.
To retrieve that data again, convert the values into Decryption
Here is the small example for Encryption and Decryption Class.
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Imports System.Windows.Forms
Public Class EncryptDecrypt
Private Shared DESProvider As New TripleDESCryptoServiceProvider
Private Shared MD5Provider As New MD5CryptoServiceProvider
Public Shared Function MD5Hash(ByVal value As String) As Byte()
Return MD5Provider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value))
End Function
Public Shared Function EncryptString(ByVal stringToEncrypt As String, ByVal key As String) As String
DESProvider.Key = Crypto.MD5Hash(key)
DESProvider.Mode = CipherMode.ECB
Dim Buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt)
Return Convert.ToBase64String(DESProvider.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
End Function
Public Shared Function DecryptString(ByVal encryptedString As String, ByVal key As String) As String
Try
DESProvider.Key = Crypto.MD5Hash(key)
DESProvider.Mode = CipherMode.ECB
Dim Buffer As Byte() = Convert.FromBase64String(encryptedString)
Return ASCIIEncoding.ASCII.GetString(DESProvider.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
MessageBox.Show("Invalid Key ", " Decryption Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return ""
End Try
End Function
End Class
How to Use:
1. Add New Class to your vb.net project with the name "EncryptDecrypt"
2. Paste the above code to your new class
You can use this class anywhere in your application
Example
Encryption: - EncryptDecryp.EncryptString("Jyothi","")
Decryption :-EncryptDecryp.DecryptString(Encryptstring,"")
Crypto.MD5Hash or EncryptDecrypt.MD5Hash ?
ReplyDeleteHi
DeleteCrypto.MD5Hash in Class