Ruby OpenSSL::Cipher::CipherError (key not set) - asp.net

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 ?)

Related

The parameter is incorrect while rsa.Decrypt

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 = #"PABSAFMAQQBLAGUAeQBWAGEAbAB1AGUAPgA8AE0AbwBkAHUAbAB1AHMAPgBxAGcAMwA3AFYAUQA1AE8AdQBuADQAMwBDAEIAbQBkAEMATQB4AFMASQB6ADkAYQA2AHoAdgBMAEgAMAA5A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4ATQB2AEEAQQBoAGwATQBFAD0APAAvAEQAPgA8AC8AUgBTAEEASwBlAHkAVgBhAGwAdQBlAD4A";
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);
}

System.Security.Cryptography.CryptographicException: Specified key is not a valid size for this algorithm

With an AES key that I retrieve from a Key Vault I'm trying to decrypt a blob file. But I keep getting:
System.Security.Cryptography.CryptographicException: Specified key is
not a valid size for this
I'm trying to reverse engineer a python decrypt situation and this suggests to me that the value I'm retrieving from the key vault is a hex string or at least should be stored as hexstrings in a bytearray.
Python:
aes_key= bytes.fromhex(aes_key)
So because I get it from my configuration with var keyStringValue = _configuration.GetValue<string>("the-key-i-want"); I first convert to a bytearray to be able to convert it to hexstring. And then put it in a bytearray again.
//Where I convert my Keyvault keyStringValue to a hexString encoded bytearray
byte[] tempBytes = utf8.GetBytes(keyStringValue);
var hexString = BitConverter.ToString(tempBytes);
hexString = hexString.Replace("-", "").ToLower();
int NumberChars = hexString.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
byte[] pass = bytes;
I pass the pass variable to my decrypt function which looks like this:
var crypto = new AesCryptographyService();
var decryptedData = crypto.Decrypt(postSplitByteArray, pass, iv)
And finally my decrypt:
public class AesCryptographyService
{ public byte[] Decrypt(byte[] data, byte[] key, byte[] iv)
{
using var aes = Aes.Create();
aes.Padding = PaddingMode.Zeros;
aes.Mode = CipherMode.CBC;
aes.Key = key;
aes.IV = iv;
using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
{
return PerformCryptography(data, decryptor);
}
}
private byte[] PerformCryptography(byte[] data, ICryptoTransform cryptoTransform)
{
using (var ms = new MemoryStream())
using (var cryptoStream = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return ms.ToArray();
}
}
The hexstring is 128 characters long. And the resultant bytearray 64. Now I know that the array should only be 32 bytes big. But I can't see the point of just cutting my key to size. Nor do I get a properly decrypted result. This bugs me since the python function seems to be doing the same as I am.
cipher = AES.new(aes256_key, AES.MODE_CBC, iv)
decrypted_data = cipher.decrypt(encrypted_data).decode('utf-8')
PS. I verified with an online converter that the conversion from string to hexstring is going well.
The solution was to not first convert my string into a bytearray and then do a hexstring conversion.
The string in the keyvault was already a "hexstring"
So getting rid of this.
byte[] tempBytes = utf8.GetBytes(keyStringValue);
var hexString = BitConverter.ToString(tempBytes);
hexString = hexString.Replace("-", "").ToLower();
And from
var keyStringValue = _configuration.GetValue<string>("the-key-i-want")
pass that to the hexstring conversion
private static byte[] FromHex(string keyStringValue)
{
int NumberChars = keyStringValue.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(keyStringValue.Substring(i, 2), 16);
return bytes;
}
And Bob is your uncle.

Datatype of encrypted password

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

sessionKey using nonce (client) and nonce(server) based on KDF2

I am working on a project. Client have common authentication system. I have to generate a nonce from my web server, encrypt using public key of authentication system, and sing using my webserver private key and post to the authentication system (XML base64 encoded). Authentication system decrypt using their private key, generate a nonce encrypt using my public key and and send back to my webserver in response. my webserver decrypt the response using my private key.
Now next step is to construct a sessionKey using nonce (client) and nonce(server) based on KDF2 algorithm. I am using asp.net 4.0 .. not able to understand and find any kind of help on "sessionKey using nonce (client) and nonce(server) based on KDF2 " in asp.net.
protected void ButtonLogin_Click()
{
string datatopost = CreatEncryptandSignXML();
PostxmltoCommongateway(datatopost);
}
public string CreatEncryptandSignXML()
{
string ClientNonce = null;
ClientNonce = Guid.NewGuid().ToString("N");
Session["ClientNonce"] = ClientNonce;
byte[] bytesToEncode = Encoding.UTF8.GetBytes(ClientNonce);
string encodednonce = Convert.ToBase64String(bytesToEncode);
string xml = "<?xml version=\"1.0\"?><root><LoginRequest>Nonce=" + encodednonce + "</LoginRequest></root>";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xml);
doc.PreserveWhitespace = true;
// Sing XML using private key ------------------------------------------------------------
System.Security.Cryptography.X509Certificates.X509Certificate2 commonauthpublickey =
new System.Security.Cryptography.X509Certificates.X509Certificate2
(#"C:\commonauthserver\publickey\sample.cer");
System.Xml.XmlElement elementToEncrypt = doc.GetElementsByTagName("LoginRequest")[0] as System.Xml.XmlElement;
System.Security.Cryptography.Xml.EncryptedXml encXML = new System.Security.Cryptography.Xml.EncryptedXml();
System.Security.Cryptography.Xml.EncryptedData data = encXML.Encrypt(elementToEncrypt, commonauthpublickey);
System.Security.Cryptography.Xml.EncryptedXml.ReplaceElement(elementToEncrypt, data, false);
// Sign XML using Private Key ---------------------------------------------------------------
System.Security.Cryptography.X509Certificates.X509Certificate2 mywerbserverprivatekey =
new System.Security.Cryptography.X509Certificates.X509Certificate2
(#"C:\mywebserver\privatekey\mywebserver.pfx","samplepasword");
System.Security.Cryptography.Xml.SignedXml sign = new System.Security.Cryptography.Xml.SignedXml(doc);
System.Security.Cryptography.Xml.KeyInfo keyInfo = new System.Security.Cryptography.Xml.KeyInfo();
sign.SigningKey = mywerbserverprivatekey.PrivateKey;
System.Security.Cryptography.Xml.KeyInfoX509Data keyInfoData = new System.Security.Cryptography.Xml.KeyInfoX509Data();
keyInfoData.AddIssuerSerial(mywerbserverprivatekey.Issuer, mywerbserverprivatekey.GetSerialNumberString());
keyInfo.AddClause(keyInfoData);
sign.KeyInfo = keyInfo;
System.Security.Cryptography.Xml.Reference reference = new System.Security.Cryptography.Xml.Reference();
reference.Uri = "";
System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform env = new
System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
sign.AddReference(reference);
sign.ComputeSignature();
System.Xml.XmlElement signedElement = sign.GetXml();
signedElement.Prefix = "ds";
doc.DocumentElement.AppendChild(signedElement);
return doc.InnerXml;
}
void PostxmltoCommongateway(string encData)
{
string URLAuth = "http://commonauth.com/getway/commomauth.do";
byte[] bytesToEncode = Encoding.UTF8.GetBytes(encData);
string encodedText = Convert.ToBase64String(bytesToEncode);
string encodedXML = HttpUtility.UrlEncode(encodedText);
string postString = string.Format("encryptedData={0}", encodedXML);
const string contentType = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.Expect100Continue = false;
CookieContainer cookies = new CookieContainer();
HttpWebRequest webRequest = WebRequest.Create(URLAuth) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = contentType;
webRequest.CookieContainer = cookies;
webRequest.ContentLength = postString.Length;
webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();
try
{
WebResponse response = webRequest.GetResponse();
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
webRequest.GetResponse().Close();
string servernonce = DecryptResponse(responseData);
string clientnonce = Session["ClientNonce"].ToString();
/// here i have to generate a sessionKey using nonce (client) and nonce(server) based on KDF2
// CreateSessionkeybasedonKDF2(servernonce,clientnonce)
}
catch (Exception ex)
{
LabelMessage.Text = ex.Message;
}
}
public string DecryptResponse(string response)
{
System.Security.Cryptography.X509Certificates.X509Certificate2 mywerbserverprivatekey =
new System.Security.Cryptography.X509Certificates.X509Certificate2
(#"C:\mywebserver\privatekey\mywebserver.pfx", "samplepasword");
RSACryptoServiceProvider.UseMachineKeyStore = false;
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)mywerbserverprivatekey.PrivateKey;
byte[] decrypted = rsa.Decrypt(Convert.FromBase64String(response), false);
return ASCIIEncoding.UTF8.GetString(decrypted);
}
Thank you for your response in advance.
KDF2 is the key seed (any length, should represent a key with enough entropy) postfixed by a 4 byte counter value in BigEndian notation, starting with value 1. So that would be KEY_SEED|00000001 for the first key. After the concatenation the value is hashed using a secure hash algorithm like SHA-1 (the hash to be used is configurable). Then you take the X leftmost bits or bytes you require from the resulting hash value.
I can only tell you how to implement KDF2 as it is not often included in cryptographic API's, I'm afraid you have to do the implementation and testing yourself (that's "too localized" anyway).

MembershipProvider.ValidateUser password encoding implementations

I'm implementing the ValidateUser method on a custom MembershipProvider class. I've seen quite a few examples of this, I'm looking for some guidance on how to properly encode/hash/encrypt my passwords. I'm no crypto expert, and I'm a little anxious about straying from the default implementation. Should I just copy the relevant source code from the SqlMembershipProvider or will any of these work?
http://mattwrock.com/post/2009/10/14/Implementing-custom-Membership-Provider-and-Role-Provider-for-Authinticating-ASPNET-MVC-Applications.aspx
public override bool ValidateUser(string username, string password)
{
if(string.IsNullOrEmpty(password.Trim())) return false;
string hash = EncryptPassword(password);
User user = _repository.GetByUserName(username);
if (user == null) return false;
if (user.Password == hash)
{
User = user;
return true;
}
return false;
}
protected string EncryptPassword(string password)
{
// Produses an MD5 hash string of the password
//we use codepage 1252 because that is what sql server uses
byte[] pwdBytes = Encoding.GetEncoding(1252).GetBytes(password);
byte[] hashBytes = System.Security.Cryptography.MD5.Create().ComputeHash(pwdBytes);
return Encoding.GetEncoding(1252).GetString(hashBytes);
}
ASP.NET membership salt?
public string EncodePassword(string pass, string salt)
{
byte[] bytes = Encoding.Unicode.GetBytes(pass);
byte[] src = Encoding.Unicode.GetBytes(salt);
byte[] dst = new byte[src.Length + bytes.Length];
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
byte[] inArray = algorithm.ComputeHash(dst);
return Convert.ToBase64String(inArray);
}
ASP.NET membership salt?
private const int ITERATIONS = 10000;
private const int SALT_SIZE = 32;
private const int HASH_SIZE = 32;
public void SaltAndHashPassword(string password, out byte[] salt, out byte[] hash)
{
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(password, SALT_SIZE, ITERATIONS);
salt = rdb.Salt;
hash = rdb.GetBytes(HASH_SIZE);
}
ASP.NET membership salt?
internal string GenerateSalt()
{
byte[] buf = new byte[16];
(new RNGCryptoServiceProvider()).GetBytes(buf);
return Convert.ToBase64String(buf);
}
internal string EncodePassword(string pass, int passwordFormat, string salt)
{
if (passwordFormat == 0) // MembershipPasswordFormat.Clear
return pass;
byte[] bIn = Encoding.Unicode.GetBytes(pass);
byte[] bSalt = Convert.FromBase64String(salt);
byte[] bAll = new byte[bSalt.Length + bIn.Length];
byte[] bRet = null;
Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length);
Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length);
if (passwordFormat == 1)
{ // MembershipPasswordFormat.Hashed
HashAlgorithm s = HashAlgorithm.Create("SHA1");
// Hardcoded "SHA1" instead of Membership.HashAlgorithmType
bRet = s.ComputeHash(bAll);
}
else
{
bRet = EncryptPassword(bAll);
}
return Convert.ToBase64String(bRet);
}
Download BCrypt.Net. As opposed to typica SHA hashing, which is too fast making anything encrypted with it easy to brute force. BCrypt is slower due to a configurable work factor, so whilst imperceptable to the user, when trying to brute force 700m keys a second, you simply can't.
Once you have bcrypt all you need to do to hash is:
...
private static readonly int BCRYPT_WORK_FACTOR = 10;
string hashedPassword = BCrypt.Net.BCrypt.HashPassword(account.HashedPassword, BCRYPT_WORK_FACTOR);
...
and to check a password:
bool matched = BCrypt.Net.BCrypt.Verify(password, match.HashedPassword))
More info here: http://www.danharman.net/2011/06/25/encrypting-hashing-passwords-for-your-website/
I use next:
var salt = Encoding.UTF8.GetBytes(this.Name);
var bytes = Encoding.UTF8.GetBytes(password);
return Convert.ToBase64String(new HMACSHA1(salt).ComputeHash(bytes));

Resources