ECDH public and private keys generation with .Net C# - c#

I am porting nodejs code to .Net and I am stuck at this part where I need to generate public and private keys.
Javascript code:
const dh = crypto.createECDH('prime256v1');
let privk = dh.getPrivateKey();
let pubk = dh.getPublicKey();
I tried the same with .Net C# with
var ecdh = new ECDiffieHellmanCng(CngKey.Create(CngAlgorithm.ECDiffieHellmanP256, null, new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport }));
var privateKey = ecdh.Key.Export(CngKeyBlobFormat.EccPrivateBlob);
var publickey = ecdh.Key.Export(CngKeyBlobFormat.EccPublicBlob);
However when I tried to exchange those keys generated with C# with the Google FCM server, I got invalid argument error. When I copy the generated byte[] array from nodejs to .Net C# code as constants it works. It is obvious that generated keys are not meeting the requirement of the server. Since I am working with undocumented interface I can't tell why the keys are not accepted. I can see that the keys generated with nodejs are in 32 bytes in length for the private key and 65 bytes in length for the public key. The keys generated from C# are 140 and 96 bytes in length. How to generate keys in C# to match the key properties in nodejs?

I was able to solve my problem using Bouncy Castle
ECKeyPairGenerator gen = new ECKeyPairGenerator("ECDH");
SecureRandom secureRandom = new SecureRandom();
X9ECParameters ecp = NistNamedCurves.GetByName("P-256");
ECDomainParameters ecSpec = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed());
ECKeyGenerationParameters ecgp = new ECKeyGenerationParameters(ecSpec, secureRandom);
gen.Init(ecgp);
AsymmetricCipherKeyPair eckp = gen.GenerateKeyPair();
ECPublicKeyParameters ecPub = (ECPublicKeyParameters)eckp.Public;
ECPrivateKeyParameters ecPri = (ECPrivateKeyParameters)eckp.Private;
byte[] publicKeyBytes = ecPub.Q.GetEncoded();

You can use ECDiffieHellman to encrypt messages. You have two options: Static-static ECDH and static-ephemeral ECDH:
For static-static ECDH the receiver will need to know the sender's public key (this might or might not be an option in your application). You should also have some data that is unique for this message (it might be a serial-number you get from somewhere else in the protocol or database-row or whatever or it might be a nonce). You then use ECDH to generate a secret key and use that to encrypt your data. This will give you your desired encrypted data length of 16 bytes, but it is not completely asymmetric: the encryptor is also able to decrypt the messages (again: this might or might not be a problem in your application).
Static-ephemeral is a bit different: here the encryptor generates a temporary (ephemeral) EC key pair. He then uses this key pair together with the receiver's public key to generate a secret key which can be used to encrypt the data. Finally, he sends the public key of the ephemeral key pair to the receiver together with the encrypted data. This might fit better into your application, but the complete encrypted data will now be 2*32+16=80 bytes using ECDH-256 and AES (as GregS notes you can save 32 bytes by only sending the x-coordinate of the public-key, but I do not believe that .NET exposes the functionality to recalculate the y-coordinate).
Here is a small class that will do static-static ECDH:
public static class StaticStaticDiffieHellman
{
private static Aes DeriveKeyAndIv(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey, byte[] nonce)
{
privateKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
privateKey.HashAlgorithm = CngAlgorithm.Sha256;
privateKey.SecretAppend = nonce;
byte[] keyAndIv = privateKey.DeriveKeyMaterial(publicKey);
byte[] key = new byte[16];
Array.Copy(keyAndIv, 0, key, 0, 16);
byte[] iv = new byte[16];
Array.Copy(keyAndIv, 16, iv, 0, 16);
Aes aes = new AesManaged();
aes.Key = key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
return aes;
}
public static byte[] Encrypt(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey, byte[] nonce, byte[] data){
Aes aes = DeriveKeyAndIv(privateKey, publicKey, nonce);
return aes.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
}
public static byte[] Decrypt(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey, byte[] nonce, byte[] encryptedData){
Aes aes = DeriveKeyAndIv(privateKey, publicKey, nonce);
return aes.CreateDecryptor().TransformFinalBlock(encryptedData,0, encryptedData.Length);
}
}
// Usage:
ECDiffieHellmanCng key1 = new ECDiffieHellmanCng();
ECDiffieHellmanCng key2 = new ECDiffieHellmanCng();
byte[] data = Encoding.UTF8.GetBytes("TestTestTestTes");
byte[] nonce = Encoding.UTF8.GetBytes("whatever");
byte[] encryptedData = StaticStaticDiffieHellman.Encrypt(key1, key2.PublicKey, nonce, data);
Console.WriteLine(encryptedData.Length); // 16
byte[] decryptedData = StaticStaticDiffieHellman.Decrypt(key2, key1.PublicKey, nonce, encryptedData);
Console.WriteLine(Encoding.UTF8.GetString(decryptedData));

Related

Public and Private Key as variables C#

I'm writing a function where this function is receiving my public key as variable, and the value for this variable is the actually public key. I need two different functions apps in Azure, to encrypt and decrypt. The keys must match, but the problem is, every time I call the API the public key is different, I can encrypt without problems. But when I have to decrypt it doesn't work. I am not able to use the same key pairs for these functions. Thats why Im trying to use the keys I generated before as variables.
Example:
string publicKey = "MMMFisIDUDHfhHSANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi7ZOKtc55v9NJuhQFR583BcFkcjflXNVMqC5/3b7t7v..."
This is the method I'm using to encrypt:
cipher.Init(true, publicKey);
My keys are being generated using Bouncy Castle.
RsaKeyPairGenerator g = new RsaKeyPairGenerator();
g.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
AsymmetricCipherKeyPair keyPair = g.GenerateKeyPair();
It worked normally with the code below:
string plainText = "test data here";
byte[] plainTextToByte = Encoding.UTF8.GetBytes(plainText);
//Generating Key Pair
RsaKeyPairGenerator g = new RsaKeyPairGenerator();
g.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
AsymmetricCipherKeyPair keyPair = g.GenerateKeyPair();
//Extracting the private key from pair
RsaKeyParameters privateKey = (RsaKeyParameters)keyPair.Private;
RsaKeyParameters publicKey = (RsaKeyParameters)keyPair.Public;
//Encryption proccess
IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());
cipher.Init(true, publicKey);
byte[] cipherText = cipher.ProcessBlock(plainTextToByte, 0, plainTextToByte.Length);
string encryptedText = Encoding.UTF8.GetString(cipherText);
Console.WriteLine(encryptedText);
//Decryption Process
cipher.Init(false, privateKey);
byte[] decryptedText = cipher.ProcessBlock(cipherText, 0 , cipherText.Length);
string decryptedTextToString = Encoding.UTF8.GetString(decryptedText);
Console.WriteLine(decryptedTextToString);
Console.ReadLine();`
I need the keys generated above as a variable to use in a function inside a console app.
But when I try pass the key as variable, I'm getting the error below:
https://i.stack.imgur.com/vLSOL.png
I could do same procedure using core classes from C#, it was similar with the code below:
C# RSA encryption/decryption with transmission
The same logic I follow for the example above is not working for me now. I am beginner into all this.
Is there a way to do that?
This is the piece code I'm using to get the error on the screenshot. The keys were generated with the code I posted on the original post.
string plainText = "test here";
byte[] plainTextToByte = Encoding.UTF8.GetBytes(plainText);
string publicKey = "MIIBIjANBgk...DAQAB";
IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());
cipher.Init(true, publicKey);
byte[] cipherText = cipher.ProcessBlock(plainTextToByte, 0, plainTextToByte.Length);
string encryptedText = Encoding.UTF8.GetString(cipherText);
Console.WriteLine(encryptedText);
return new OkObjectResult(encryptedText);`
Att.
I'm not quite clear what the problem is. But based on the last snippet posted in the question, you are trying to import a public key. And according to your penultimate comment, it is a PEM encoded public key in X.509/SPKI format exported with a PemWriter:
-----BEGIN PUBLIC KEY-----
MIIB...
...AQAB
-----END PUBLIC KEY-----
Such a key can be imported and used in Cipher#Init() as follows (let publicKeyPem be the exported PEM key):
using Org.BouncyCastle.OpenSsl;
...
PemReader pemReader = new PemReader(new StringReader(publicKeyPem));
RsaKeyParameters publicKeyReloaded = (RsaKeyParameters)pemReader.ReadObject();
...
cipher.Init(true, publicKeyReloaded);

CryptSharp SCrypt implementation in C#

I'm working on a CryptSharp SCrypt implementation in VS2015. I need to encrypt/decrypt text files meant to be sent as email attachments. Initially I was using AES but considering that HMAC-SHA1 is outdated I opted to use SCrypt for password hashing. However, SCrypt does not expose public methods for the data encryption itself, so would it make sense to pass the SCrypt hashed password to AES, then use the latter for data encryption? Or perhaps there is a better approach?
In this scenario, I would imagine something like this, yet I would need to find a way to reliably randomize the IV...
private static Aes SetAes(string userName, string password)
{
var passBytes = Encoding.UTF8.GetBytes(password);
var saltBytes = Encoding.UTF8.GetBytes(userName);
var cost = 131072; // around 5 secs with block at 16(on Xeon 1241 v3)
var blockSize = 16; // 8 is default but might not suffice against modern GPUs(?)
var parallel = 1;
var maxThreads = (int?)null;
byte[] derivedKey = new byte[32]; // 256 bits
SCrypt.ComputeKey(passBytes, saltBytes, cost, blockSize, parallel, maxThreads, derivedKey);
Aes aes = new AesManaged();
aes.Padding = PaddingMode.PKCS7;
aes.Key = derivedKey;
byte[] IV = new byte[16];
Array.Copy(derivedKey, IV, 16); // how to reliably randomize the IV?
aes.IV = IV;
return aes;
}
Then for file encryption:
internal static void EncryptText(string text, string userName, string password, string file)
{
// omitting argument checks for readability
using (Aes aes = SetAes(userName, password))
{
using (FileStream fileStream = new FileStream(file, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
using (CryptoStream cryptoStream = new CryptoStream(fileStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(cryptoStream, text); // I'm using a class to wrap the text for serialization, not shown here for readability
}
}
}
}
Even though it seems to work, I'm not sure it makes sense, so thank you very much for any insight.
EDIT:
Following vcsjones recommendations, the SetAes function would rather look like this, if I understand correctly:
private static Aes SetAes(string userName, string password, byte[] IV = null)
{
var passBytes = Encoding.UTF8.GetBytes(password);
var saltBytes = Encoding.UTF8.GetBytes(userName);
var cost = 131072;
var blockSize = 16;
var parallel = 1;
var maxThreads = (int?)null;
byte[] derivedKey = new byte[32];
SCrypt.ComputeKey(passBytes, saltBytes, cost, blockSize, parallel, maxThreads, derivedKey);
Aes aes = new AesManaged();
aes.Padding = PaddingMode.PKCS7;
aes.Key = derivedKey;
if (IV == null) // when encrypting, generate IV
{
RandomNumberGenerator rn = RandomNumberGenerator.Create();
rn.GetBytes(aes.IV);
}
else aes.IV = IV; // when decrypting, read IV from file and pass it to aes through IV parameter for decryption
return aes;
}
However, SCrypt does not expose public methods for the data encryption itself, so would it make sense to pass the SCrypt hashed password to AES
SCrypt is a Key Derivation Function, so yes, that is an acceptable thing to do.
how to reliably randomize the IV?
Don't use the output of the KDF in the IV. The IV should be random for AES-CBC, so use RandomNumberGenerator.Create() to create a CSPRNG for the IV. Using the KDF output as part of the IV actually leaks the key since the IV is stored in plaintext.
An IV in AES-CBC should be random, and it should not be reused. Don't derive it from the password. You do need to store the IV somewhere. Since it looks like you're trying to encrypt files, you may just want to put the IV in at the beginning of the file. The IV is not a secret - it's OK if someone can read it. Then, when it comes time to decrypt the file, read the IV from the file, and then decrypt everything past the IV.
I would also recommend that you MAC the file, as well, as right now your application does not authenticate the encryption.

String encryption in Objective-C decrypt in C#

I am building a iPhone app which uses a c# web service. My iPhone app takes in some data and encrypts it and passes it to the web service. How do I decrypt the data in C#?
My iPhone app contains the following code:
NSString *pString = #"Some string to be encoded";
NSString *key = #"My encryption key";
NSData *pData = [pString dataUsingEncoding:NSUTF8StringEncoding];
pData = [pData AES256EncryptWithKey:key];
NSString *pID = [pData base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
EDIT: The data is already stored in the web service so I can't readily change the encryption approach. The C# application is not on the server so there is no possibility of compromising the key.
I have tried the following C# code to decrypt the data:
static string DecryptString(string encryptedText, string key)
{
byte[] encryptedString = Convert.FromBase64String(encryptedText);
byte[] encryptionKey = Encoding.UTF8.GetBytes(key.Substring(0, 32));
using (var provider = new AesCryptoServiceProvider())
{
provider.Mode = CipherMode.CBC;
provider.Padding = PaddingMode.PKCS7;
provider.Key = encryptionKey;
using (var ms = new MemoryStream(encryptedString))
{
// Read the first 16 bytes which is the IV.
byte[] iv = new byte[16];
ms.Read(iv, 0, 16);
provider.IV = iv;
using (var decryptor = provider.CreateDecryptor())
{
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (var sr = new StreamReader(cs))
{
return sr.ReadToEnd();
}
}
}
}
}
}
However, I get the following exception:
System.Security.Cryptography.CryptographicException was unhandled
HResult=-2146233296 Message=Padding is invalid and cannot be
removed.
The encryptedText received by DecryptString is 80 bytes in length.
The sample ObjC code uses by default CBC modem, PKCS#7 padding and a default iv of 16 0x00 bytes.
The C# also uses CBC mode and PKCS#7 padding. The decryption code expects a 16-byte iv pre-pended to the encrypted data and that does not exist.
byte[] iv = new byte[16];
ms.Read(iv, 0, 16);
provider.IV = iv;
This needs to be changed so that iv is set to an array of 16 0x00 bytes and the ms.Read(iv, 0, 16) statement needs to be deleted so the decrypt function gets all of the encrypted data.
Notes:
Using a devault anything in encryption is a bad idea, always provide the correect length data.
Authentication of the encrypted data needs should be added so that it can be determined if there an incorrect key or the data has been tampered with.
There really should be a version number and a random IV used and prepended to the encrypted so you should really consider correcting this. This demonstrates why a version number generally needs to be provided and used.
RNCryptor covers the above issues.
The handling of the encryption key also needs to be considered so that is is as secure as necessary.
You need to first decode the base-64 encoded string to a byte[] - see Convert.FromBase64String(). Then you need to use the Aes class to decrypt it - there's an example on its documentation page.

Encrypt in Coldfusion and decrypt in C#

Here is the code used to encrypt in coldfusion
<cfset strBase64Value = encrypt(strValue,24 character key,AES) />
It is generating encrypted values like 714FEA9A9A2184769CA49D5133F08580 which seems odd to me considering it is only uppercase and numbers.
What C# library should I use to properly decrypt it ?
Also looking at this information, it seems that by default it uses the UUEncode algorithm to encode.
Should I ask the encrypter to use Base64 as encoding parameter ?
It is generating encrypted values like 714FEA9A9A2184769CA49D5133F08580
Then they are using "Hex", not the default "UUEncode". Either "hex" or "base64" is fine. As long as you both agree upon the encoding, it does not really matter.
You can use RijndaelManaged to decrypt the strings. However, the default encryption settings for ColdFusion and C# differ slightly. With the encrypt function:
"AES" is short for "AES/ECB/PKCS5Padding"
"ECB" mode does not use an IV
Key strings are always base64 encoded
NB: Despite the name difference, for the SUN provider, PKCS5Padding (CF/Java) corresponds to PaddingMode.PKCS7 (C#). As mentioned in this thread, the "... SUN provider in Java indicate[s] PKCS#5 where PKCS#7 should be used - "PKCS5Padding" should have been "PKCS7Padding". This is a legacy from the time that only 8 byte block ciphers such as (triple) DES symmetric cipher were available."
So you need to ensure your C# settings are adjusted to match. With that in mind, just decode the encrypted text from hex and the key string from base64. Using the slightly ugly example in the API, just adjust the algorithm settings to match those used by the encrypt() function:
Encrypt with ColdFusion
<cfscript>
plainText = "Nothing to see";
// 128 bit key base64 encoded
keyInBase64 = "Y25Aju8H2P5DR8mY6B0ezg==";
// "AES" is short for "AES/ECB/PKCS5Padding"
encryptedText = encrypt(plainText, keyInBase64, "AES", "hex");
WriteDump( encryptedText );
// result: 8889EDF02F181158AAD902AB86C63951
</cfscript>
Decrypt with C#
byte[] bytes = SomeMethodToConvertHexToBytes( encryptedText );
byte[] key = Convert.FromBase64String( keyInBase64 );
string decryptedText = null;
using (RijndaelManaged algorithm = new RijndaelManaged())
{
// initialize settings to match those used by CF
algorithm.Mode = CipherMode.ECB;
algorithm.Padding = PaddingMode.PKCS7;
algorithm.BlockSize = 128;
algorithm.KeySize = 128;
algorithm.Key = key;
ICryptoTransform decryptor = algorithm.CreateDecryptor();
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
decryptedText = srDecrypt.ReadToEnd();
}
}
}
}
Console.WriteLine("Encrypted String: {0}", encryptedText);
Console.WriteLine("Decrypted String: {0}", decryptedText);
Keep in mind you can (and probably should) adjust the settings, such as using the more secure CBC mode instead of ECB. You just need to coordinate those changes with the CF developer.
If anyone had similar problem with JAVA I just implemented encryption and decryption of string previously encrypted/decrypted in coldfusion with "Hex" and "tripledes". Here is my code:
private static final String PADDING = "DESede/ECB/PKCS5Padding";
private static final String UTF_F8 = "UTF-8";
private static final String DE_SEDE = "DESede";
private String secretKey;
public String encrypt(String message) throws Exception {
secretKey = getSecretKey();
final byte[] secretBase64Key = Base64.decodeBase64(secretKey);
final SecretKey key = new SecretKeySpec(secretBase64Key, DE_SEDE);
final Cipher cipher = Cipher.getInstance(PADDING);
cipher.init(Cipher.ENCRYPT_MODE, key);
final byte[] plainTextBytes = message.getBytes();
final byte[] cipherText = cipher.doFinal(plainTextBytes);
return Hex.encodeHexString(cipherText);
}
public String decrypt(String keyToDecrypt) throws Exception {
secretKey = getSecretKey();
byte[] message = DatatypeConverter.parseHexBinary(keyToDecrypt);
final byte[] secretBase64Key = Base64.decodeBase64(secretKey);
final SecretKey key = new SecretKeySpec(secretBase64Key, DE_SEDE);
final Cipher decipher = Cipher.getInstance(PADDING);
decipher.init(Cipher.DECRYPT_MODE, key);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, UTF_F8);
}

TripleDES Encryption in Windows Store app (Windows 8.1)

I want to encrypt some text using TripleDES Encryption with ECB cipher mode in Windows Store app (Windows 8.1) but I am having issues in creating a key for symmetric algorithm.
I would like to tell you what I am currently doing in .NET 4.5
public static string EncryptData(string Message, string passphrase)
{
byte[] tpinBytes = System.Text.Encoding.ASCII.GetBytes(Message);
string tpinHex = ByteArrayHelper.ByteArrayToHexString(tpinBytes);
byte[] Results;
byte[] TDESKey = ByteArrayHelper.HexStringToByteArray(passphrase);
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.Zeros;
byte[] DataToEncrypt = ByteArrayHelper.HexStringToByteArray(tpinHex);
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
}
return ByteArrayHelper.ByteArrayToHexString(Results);
}
Now, I have written this code snippet for my Windows Store (Windows 8.1) app;
private static string TripleDESEncryption(string strMsg, string passphrase)
{
String strAlgName = SymmetricAlgorithmNames.TripleDesEcb;
var bytes = System.Text.Encoding.UTF8.GetBytes(strMsg);
string hex = BitConverter.ToString(bytes).Replace("-", "");
// Initialize the initialization vector
IBuffer iv = null;
// Create a buffer that contains the encoded message to be encrypted.
IBuffer DataToEncrypt = CryptographicBuffer.DecodeFromHexString(hex);
// Open a symmetric algorithm provider for the specified algorithm.
SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);
// Create a symmetric key.
IBuffer TDESKey = CryptographicBuffer.DecodeFromHexString(passphrase);
CryptographicKey key = objAlg.CreateSymmetricKey(TDESKey); // Line of problem.
// Encrypt the data and return.
IBuffer buffEncrypt = CryptographicEngine.Encrypt(key, DataToEncrypt, iv);
return CryptographicBuffer.EncodeToHexString(buffEncrypt);
}
When I match the values of TDESKey and EncryptData, they are identical. However, the issue occurs when I try to create symmetric key (after TDESKey assignment). It gives me an error of Value does not fall within the expected range and according to MSDN forums, the block size may not be supported (which I am unable to understand) and it does not even have those properties which are listed in that forum (for e.g. SupportedKeyLengths).
Can anyone help me out with the sample or point out the mistake I have been making?
WinRT does not support 16-byte keys. Try a 24-byte key.

Categories

Resources