I want to encrypt my password and store to my DB, SQL Server 2008 R2.
For that I took the password from text box and encrypted using proper function and want to store in back end.
Tell me which datatype I have to use for encrypted password column.
Namespace:
using System.Security.Cryptography;
Encrypt Function:
public static string Encrypt(string Message)
{
string Password = Message;
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Password));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToEncrypt = UTF8.GetBytes(Message);
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
}
Decrypt Function:
public static string Decrypt(string Message)
{
string Password = Message;
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Password));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
}
How to use??
For Encrypt:
string encryptpassword=Encrypt(txtPassword.Text.Trim());
For Decrypt:
string decryptpassword=Decrypt(txtPassword.Text.Trim());
NOTE : txtPassword is a textbox where you can enter a password
Related
getting an error "The parameter is incorrect" while using rsa.Decrypt method the public/private key is same while encrypt/decrypt. can someone help me where I'm doing wrong?
private const string Key = #"PABSAFMAQQBLAGUAeQBWAGEAbAB1AGUAPgA8AE0AbwBkAHUAbAB1AHMAPgBxAGcAMwA3AFYAUQA1AE8AdQBuADQAMwBDAEIAbQBkAEMATQB4AFMASQB6ADkAYQA2AHoAdgBMAEgAMAA5AGcAQgBvAG0AQwA1AEwARgBTAFkASABJAEcAZgAvAEUAZQBTAE4ASgBWAHUALwBBAEwAegBxAEgAYwA2AGIAcwBrAFgAbwBRAEIAZgBPAEUAMQBEAGMAVABKAEkATgBZAHAAWAByAFMALwBmAG4AcQBtAC8AUAB0AGQAcgBzAFcAeAB2AGEAWABwAHMARABTAG0AZwBhAEwASgBTAEEAZgBHAEkAYQA2ADUAdABCAHkAQgB6AE8AOAB0AFcAdABYAC8AaABQAG4ATABZAG0AdwBXAGoASgBFADQAQgB5AG0AUAArAC8AdABZAFIAdAB3AHMAbQBYAG4AdQBtAEkAbgA3ADQATQBTADMANAB6AGYAdgByAGcAcwA9ADwALwBNAG8AZAB1AGwAdQBzAD4APABFAHgAcABvAG4AZQBuAHQAPgBBAFEAQQBCADwALwBFAHgAcABvAG4AZQBuAHQAPgA8AFAAPgAyAEkAZQBBAGIATwBRAEkASQBzAG0AQwBTAGEAYgBCAG8AdwB5AHQAUwB0AFMAWQBZAHkAKwBLAG0AMQBYAFcASAB6AGUAWAA3AC8AMgBCADEAbgBUAGoAaABvAFYAZwA4AHMARgBxAEcAdgB1AHIATQBTAGcAZwB0AGUAegBqAEkAZgB3AGkAYQAyAGUAMgBiAEUAeQBSAHkASgBSAG4AegB2AFYAcgA4AFEAPQA9ADwALwBQAD4APABRAD4AeQBRADIAMABjAEEAbQBrAG8AVgBrAHQANgBXAHgARABJADgAYQB2AGcAMgByAFEARgB1AEQAZgBmAGwAagBZAEgARwBhAE4AUABEAE4AdABKAG0AOABa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FAAUgA3AFIAawB0AFQAVQBuAG0AWQBvAHYAbgAzAFYANgBkADUAQQBUAHcANwAxAEgASABRAE4ANgBVAEoAWABmAHgANQBWADMAdABYADYATgBpADgAawBnAEMAUAB3AEUANABFAEkAMQBqAHoAdgBQAFgARABUAFEARQBvAGsAOABGADUANwB3AFUAbQBqAFAASQAzAFMAVwA4ADEAQgBUADIANABYAHYASAA3AHEAagBEADQATwBLAHYAZgA3AE4AKwBOAG4ATQB2AEEAQQBoAGwATQBFAD0APAAvAEQAPgA8AC8AUgBTAEEASwBlAHkAVgBhAGwAdQBlAD4A";
static void Main(string[] args)
{
string pwd = "ABC1564";
string encrypt = Encrypt(pwd);
string decrypt = Decrypt(encrypt);
Console.WriteLine("Password String :- " + pwd.ToString());
Console.WriteLine("Encrypted String :- " + encrypt.ToString());
Console.WriteLine("Decrypted String :- " + decrypt.ToString());
Console.ReadLine();
}
private static string Encrypt(string data)
{
CspParameters CSPParam = new CspParameters();
CSPParam.Flags = CspProviderFlags.UseMachineKeyStore;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(CSPParam);
rsa.FromXmlString(System.Text.UnicodeEncoding.Unicode.GetString(System.Convert.FromBase64String(Key)));
return System.Convert.ToBase64String(rsa.Encrypt((new System.Text.UnicodeEncoding()).GetBytes(data), false));
}
private static string Decrypt(string Crypt)
{
// Crypt Provider
CspParameters CSPParam = new CspParameters();
CSPParam.Flags = CspProviderFlags.UseMachineKeyStore;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(CSPParam);
// Crypt Params
string k = System.Text.UnicodeEncoding.Unicode.GetString(System.Convert.FromBase64String(Key));
rsa.FromXmlString(k);
// Decrypt
byte[] bi = (new System.Text.UnicodeEncoding()).GetBytes(System.Text.UnicodeEncoding.Unicode.GetString(System.Convert.FromBase64String(Crypt)));
byte[] bdecr = rsa.Decrypt(bi, false);
// Return results
return (new System.Text.UnicodeEncoding()).GetString(bdecr);
}
Decryption logic is missing something can you please assist.
Output is not completely decrypted.
Java Encryption Logic:
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {
try {
String in ="This is a text message";
byte[] input = in.toString().getBytes("utf-8");
String ENCRYPTION_KEY = "RW50ZXIgS2V5IEhlcmU=";
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] thedigest = md.digest(ENCRYPTION_KEY.getBytes("UTF-8"));
// SecretKeySpec skc = new SecretKeySpec(thedigest, "AES/ECB/PKCS5Padding");
SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skc);
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
// String query = Base64.encodeToString(cipherText, Base64.DEFAULT);
String query = new String(java.util.Base64.getEncoder().encode(cipherText));
System.out.println("query " + query);
// String query = new String(encode(cipherText), StandardCharsets.ISO_8859_1);
} catch(UnsupportedEncodingException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
}
Nodejs Decryption Logic:
let crypto = require('crypto');
var decipher = crypto.createDecipher('aes-256-ecb', "RW50ZXIgS2V5IEhlcmU=");
decipher.setAutoPadding(false);
console.log(decipher.update("EncyptedText", 'base64', 'utf8') + decipher.final('utf8'));
I am trying to port an existing .net encryption code to ruby. But stuck with the key not set error.
Bellow is the .net code to encrypt a string.
private static string Encrypt(string strToEncrypt, string saltValue, string password)
{
using (var csp = new AesCryptoServiceProvider())
{
ICryptoTransform e = GetCryptoTransform(csp, true, saltValue, password);
byte[] inputBuffer = Encoding.UTF8.GetBytes(strToEncrypt);
byte[] output = e.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
string encrypted = Convert.ToBase64String(output);
return encrypted;
}
}
private static ICryptoTransform GetCryptoTransform(AesCryptoServiceProvider csp, bool encrypting, string saltValue, string password)
{
csp.Mode = CipherMode.CBC;
csp.Padding = PaddingMode.PKCS7;
var passWord = password;
var salt = saltValue;
//a random Init. Vector. just for testing
String iv = "e675f725e675f123";
var spec = new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes(passWord), Encoding.UTF8.GetBytes(salt), 1000);
byte[] key = spec.GetBytes(16);
csp.IV = Encoding.UTF8.GetBytes(iv);
csp.Key = key;
if (encrypting)
{
return csp.CreateEncryptor();
}
return csp.CreateDecryptor();
}
I have used Ruby's OpenSSL::PKCS5 library to generate key and OpenSSL::Cipher to encrypt using AES algorithm like bellow.
def aes_encrypt(input_string)
cipher = OpenSSL::Cipher.new('AES-128-CBC')
cipher.encrypt
key = encryption_key
iv = cipher.random_iv
cipher.update(input_string) + cipher.final
end
def encryption_key
OpenSSL::PKCS5.pbkdf2_hmac_sha1(PASSWORD, SALT, 1000, 16)
end
Can anyone let know where I am missing? (Padding ?)
I am retrieving a text password as input from a file and applying AES encryption over that and later on, decrypting that.
When I did it for the first time, every 4 out of 5 times it was running correctly (encryption decryption successful) but 1 time, it was throwing BadPaddingException. Following is what I wrote :
//ABCD is class name
public static void enc(String fileName, String pwd) {
try {
Properties prop = new Properties();
InputStream input = ABCD.class.getClassLoader().getResourceAsStream(fileName);
prop.load(input);
input.close();
URL url = ABCD.class.getClassLoader().getResource(fileName);
FileOutputStream outputStream = new FileOutputStream(url.getPath());
KeyGenerator key = KeyGenerator.getInstance("AES");
key.init(128);
SecretKey aesKey = key.generateKey();
String newkey = new String(Base64.encode(aesKey.getEncoded()).getBytes("UTF-8"));
Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] clear = pwd.getBytes("UTF-8");
byte[] cipher = aesCipher.doFinal(clear);
String encPwd = new String(cipher);
prop.setProperty("password", encPwd);
prop.setProperty("secKey", newkey);
prop.store(outputStream, null);
outputStream.close();
} catch (Exception e) {
System.out.println(e);
}
}
public static String dec(Properties prop, String fileName) {
String decPwd = ABCD.map.get(fileName);
try {
String newkey = prop.getProperty("secKey");
StringBuilder pwd;
byte[] newkeybuff = Base64.decode(newkey.getBytes("UTF-8"));
SecretKey key = new SecretKeySpec(newkeyuff, "AES");
Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
aesCipher.init(Cipher.DECRYPT_MODE, key);
pwd = new StringBuilder(prop.getProperty("password"));
byte[] cipher = aesCipher.doFinal(pwd.toString().getBytes());
decPwd = new String(cipher);
} catch (Exception e) {
System.out.println(e);
}
ABCD.map.put(fileName, decPwd);
return decPwd;
}
I needed to fix this. Somewhere, I read that BadPaddingExcpetion occurs since of the operations done with String, in place of where actually byte should be used. Hence, I changed my code to the following :
public static void enc(String fileName, String pwd) {
try {
Properties prop = new Properties();
InputStream input = ABCD.class.getClassLoader().getResourceAsStream(fileName);
prop.load(input);
input.close();
URL url = ABCD.class.getClassLoader().getResource(fileName);
FileOutputStream outputStream = new FileOutputStream(url.getPath());
KeyGenerator key = KeyGenerator.getInstance("AES");
key.init(128);
SecretKey aesKey = key.generateKey();
byte[] newkey=(Base64.encode(aesKey.getEncoded())).getBytes("UTF-8");
Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, aesKey,new IvParameterSpec(new byte[16]));
byte[] clear = pwd.getBytes("UTF-8");
byte[] cipher = aesCipher.doFinal(clear);
prop.setProperty("password", Arrays.toString(cipher));
prop.setProperty("secKey", Arrays.toString(newkey));
prop.store(outputStream, null);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
System.out.println(e);
}
}
public static String dec(Properties prop, String fileName) {
String decPwd = ABCD.map.get(fileName);
try {
byte[] newkey=prop.getProperty("secKey").getBytes("UTF-8");
byte[] pwd;
byte[] newkeybuff = Base64.decode(newkey);
SecretKeySpec key = new SecretKeySpec(newkeybuff, "AES");
Cipher aesCipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
aesCipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(new byte[16]));
pwd = prop.getProperty("password").getBytes();
byte[] cipher = aesCipher.doFinal(pwd);
decPwd=new String(cipher);
System.out.println("Decrypted pwd " + decPwd);
}
catch (Exception e) {
System.out.println(e);
}
ABCD.map.put(fileName, decPwd);
return decPwd;
}
Now, I am getting InvalidKeyException. This time, I read that the size of the key should be 16 bytes. But I don't know how to apply this. Need a fix for this!
You should check your IV (Initialization Vector) which must be the same for encryption and decryption.
A padding error usually means the decryption failed.
Check that the key is a full length (16, 24 or 32 bytes), the IV is full length (16-bytes). If the key or IV is to short it will be padded with "something"and that man not be consistent, there is no standard for such padding.
getBytes("UTF-8") may return different length of bytes depending on the characters used.
Using new IvParameterSpec(new byte[16]) for the IV is incorrect, the IV should be a random bytes. A usual method of handling the IV is to create a random IV on encryption and prepend it to the encrypted data, it does not need to be secret and by prepending it will be available for decryption.
I want to encrypt mail id. The encrypted mail id should not contain special characters.
I send mail from console app. In console app I encode the mail id and attach it in link that will perform my click counts. In the web app I am decoding the mail id passed. So if encrypted mail id contains special character it is disturbing my link.
I am using following:
string EncryptedEmailId;
string EncryptionKey = "MAKV2SPBNI99212";
byte[] EmailIdEncrypt = Encoding.Unicode.GetBytes(InvEmail);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdbEncrypt = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdbEncrypt.GetBytes(32);
encryptor.IV = pdbEncrypt.GetBytes(16);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
csEncrypt.Write(EmailIdEncrypt, 0, EmailIdEncrypt.Length);
csEncrypt.Close();
}
EncryptedEmailId = Convert.ToBase64String(msEncrypt.ToArray());
}
}
individualContent = individualContent.Replace("[MailId]", EncryptedEmailId);
With the hint given by Nipun I got the answer.
a) Convert String to Hex
public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
{
Byte[] stringBytes = encoding.GetBytes(input);
StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
foreach (byte b in stringBytes)
{
sbBytes.AppendFormat("{0:X2}", b);
}
return sbBytes.ToString();
}
b) Convert Hex to String
public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
{
int numberChars = hexInput.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
}
return encoding.GetString(bytes);
}
Sample usage code
string testString = "MIKA#?&^";
string hex = ConvertStringToHex(testString, System.Text.Encoding.Unicode);
string normal = ConvertHexToString(hex, System.Text.Encoding.Unicode);
Debug.Assert(testString.CompareTo(normal) == 0, "They are not identical");
Have a look at: http://www.nullskull.com/faq/834/convert-string-to-hex-and-hex-to-string-in-net.aspx
You will need to try different Algo for the same
Try anyof the below methods and see if it works for you?
This won't be working you as you are using Console App, but can try other one.
string EncryptedText = FormsAuthentication.HashPasswordForStoringInConfigFile("YourPlainText", "MD5");
Or, you may use the following encryption and decryption algorithm:
using System.IO;
using System.Text;
using System.Security.Cryptography;
/// <summary>
/// Summary description for Pass
/// </summary>
public class CryptoSystem
{
public string plainText;
public string passPhrase = "Pas5pr#se";
public string saltValue = "s#1tValue";
public string hashAlgorithm = "MD5";
public int passwordIterations = 2;
public string initVector = "#1B2c3D4e5F6g7H8";
public int keySize = 256;
public string Encrypt(string plainText)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
return cipherText;
}
public string Decrypt(string cipherText)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
return plainText;
}
}
Try out Hexadecimal as well
http://www.string-functions.com/string-hex.aspx
To code follow this link
Convert string to hex-string in C#
byte[] ba = Encoding.Default.GetBytes("sample");
var hexString = BitConverter.ToString(ba);