Sunday, January 7, 2018

Encrypt and Decrypt string using SQL

Sample Code


 Declare   
 @myData nvarchar(max) = 'My data',  
 @seqKey nvarchar(20) = 'UniQKey07x@a',  
 @encryptedData varbinary(2000)  
 set @encryptedData = EncryptByPassPhrase(@seqKey, @myData)  
 print @encryptedData  
 print convert(nvarchar(max),DecryptByPassPhrase(@seqKey, @encryptedData ))--Decrypted data  

Output

 0x010000008076CB00D6FB7820D77D4B9C3768D596BA1812019E4CFCAEF9B190DAD462A3E3  
 My data  

Encrypt And Decrypt String Without Using Special Character In C#

Encrypt


 public static string Encrypt(string plainText)  
     {  
       try  
       {  
         System.Text.Encoding encoding = System.Text.Encoding.Unicode;  
         Byte[] stringBytes = encoding.GetBytes(plainText);  
         StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);  
         foreach (byte b in stringBytes)  
         {  
           sbBytes.AppendFormat("{0:X2}", b);  
         }  
         return sbBytes.ToString();  
       }  
       catch (Exception tx)  
       {  
         return "0";  
       }  
     }  

Decrypt


  public static string Decrypt(string encryptedText)  
     {  
       try  
       {  
         System.Text.Encoding encoding = System.Text.Encoding.Unicode;  
         int numberChars = encryptedText.Length;  
         byte[] bytes = new byte[numberChars / 2];  
         for (int i = 0; i < numberChars; i += 2)  
         {  
           bytes[i / 2] = Convert.ToByte(encryptedText.Substring(i, 2), 16);  
         }  
         return encoding.GetString(bytes);  
       }  
       catch (Exception ex)  
       {  
         return "0";  
       }  
     }