How to use BouncyCastle's Diffie-Hellman in C#? - c#

I'm writing an app that'll exchange data between a phone and a Windows PC, and I want to protect the data sent with key generated with a Diffie-Hellman exchange.
I'm trying to use BouncyCastle for that, but the almost non-existant documentation for the C# implementation has me stumped.
What I want to know is: what's the workflow for generating a DH key and computing a shared key when the other side's key is received? (I'm assuming I can send my key as a string and I can work with the other side's key as a string.) What objects/methods do I use in C# for that?

Alright, after a lot of trial, I got it working. Posting answer in case someone else needs it.
I'll assume the reader (1) knows what Diffie-Hellman is and what it's useful for (read here for details) and (2) already imported Bouncycastle to a .NET project via NuGet.
Imports you'll need:
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
How to generate g and p:
public DHParameters GenerateParameters()
{
var generator = new DHParametersGenerator();
generator.Init(BitSize, DefaultPrimeProbability, new SecureRandom());
return generator.GenerateParameters();
}
Wanna get g and p as strings?
public string GetG(DHParameters parameters)
{
return parameters.G.ToString();
}
public string GetP(DHParameters parameters)
{
return parameters.P.ToString();
}
How to generate a and A:
public AsymmetricCipherKeyPair GenerateKeys(DHParameters parameters)
{
var keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");
var kgp = new DHKeyGenerationParameters(new SecureRandom(), parameters);
keyGen.Init(kgp);
return keyGen.GenerateKeyPair();
}
Wanna read a and A as a string?
// This returns A
public string GetPublicKey(AsymmetricCipherKeyPair keyPair)
{
var dhPublicKeyParameters = _generatedKey.Public as DHPublicKeyParameters;
if (dhPublicKeyParameters != null)
{
return dhPublicKeyParameters.Y.ToString();
}
throw new NullReferenceException("The key pair provided is not a valid DH keypair.");
}
// This returns a
public string GetPrivateKey(AsymmetricCipherKeyPair keyPair)
{
var dhPrivateKeyParameters = _generatedKey.Private as DHPrivateKeyParameters;
if (dhPrivateKeyParameters != null)
{
return dhPrivateKeyParameters.X.ToString();
}
throw new NullReferenceException("The key pair provided is not a valid DH keypair.");
}
To import the parameters from strings just do:
var importedParameters = new DHParameters(p, g);
To generate b and B just use GenerateKeys() with importedParameters instead of the generated parameters.
Let's say you generated b and B and already got p, g and A. To compute the shared secret:
public BigInteger ComputeSharedSecret(string A, AsymmetricKeyParameter bPrivateKey, DHParameters internalParameters)
{
var importedKey = new DHPublicKeyParameters(new BigInteger(A), internalParameters);
var internalKeyAgree = AgreementUtilities.GetBasicAgreement("DH");
internalKeyAgree.Init(bPrivateKey);
return internalKeyAgree.CalculateAgreement(importedKey);
}
Repeat for A and now you have a shared secret between 2 clients, ready to be used to encrypt communications.
Hope this is useful.

An implementation of the Diffie-Hellman key agreement based on PEM file format BouncyCastle.Diffie-hellman
Example
// Public Key Alice
var pubAlice = #"-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEOkLo3q6MN3XS5xlY3OowqMkvPrYz
j4hLVJ2Wkuob3KQb1QidaAQsJ6Azy0yTuBanL4iy+dewA3YjejBMZEoh6w==
-----END PUBLIC KEY-----
";
// EC-Private Key Alice
var priAlice = #"-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIC9LMxwIwKThjtaUAJbJBCU0vFa+H8G98p/Z9JLYmEehoAoGCCqGSM49
AwEHoUQDQgAEOkLo3q6MN3XS5xlY3OowqMkvPrYzj4hLVJ2Wkuob3KQb1QidaAQs
J6Azy0yTuBanL4iy+dewA3YjejBMZEoh6w==
-----END EC PRIVATE KEY-----
";
// Public Key Bob
var pubBob = #"-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEnDMGlBFH7jbHHAYgdPR7247xqzRF
Y1HFy4HfejSgUKBxgj6biZUwSbNKuino7ObZnqrnJayWJZ7f4Eb6XuT6yQ==
-----END PUBLIC KEY-----
";
// EC-Private Key Bob
var priBob = #"-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIGqA4f7o5oBF5FgEQtNmz6fWKg/OcPPUORMX3uRc7sduoAoGCCqGSM49
AwEHoUQDQgAEnDMGlBFH7jbHHAYgdPR7247xqzRFY1HFy4HfejSgUKBxgj6biZUw
SbNKuino7ObZnqrnJayWJZ7f4Eb6XuT6yQ==
-----END EC PRIVATE KEY-----
";
var secretAlice = DiffieHellmanKeyAgreementUtil.GetPairKey(priAlice, pubBob);
var secretBob = DiffieHellmanKeyAgreementUtil.GetPairKey(priBob, pubAlice);
Console.WriteLine($"secretAlice: {secretAlice}");
Console.WriteLine($"secretBob: {secretBob}");
Output
secretAlice: RGZcMLnsXJqbQ/JGIIl61l/XpIgSL43Ync+16YKyMuQ=
secretBob: RGZcMLnsXJqbQ/JGIIl61l/XpIgSL43Ync+16YKyMuQ=

Related

How to encrypt plain text using RSA asymmetric encryption

I am working on an application where I need to encrypt plain text using the RSA algorithm. I encrypt the plain text but it is not working as it gives Error Decoding Text. Basically, I am calling third-party API which gives me the error. When I encrypt my text using this link reference link it works perfectly fine so I think I am doing something wrong. Here is my code
public static string Encryption(string strText)
{
var publicKey = #"<RSAKeyValue><Modulus>MIIDSjCCAjKgAwIBAgIEWrJUKTANBgkqhkiG9w0BAQsFADBmMQswCQYDVQQGEwJE
RTEPMA0GA1UECAwGQmF5ZXJuMQ8wDQYDVQQHDAZNdW5pY2gxDzANBgNVBAoMBkxl
eGNvbTEkMCIGA1UEAwwbQWdyb3BhcnRzX0RNU19CYXNrZXRfVXBsb2FkMCAXDTE4
MDMyMTEyNDYzM1oY################################################
A1UECAwG########################################################
################################################################
WaOa0parvIrMk9/#################################################
NCIeGu+epwg8oUCr6Wd0BNATNjt8Tk64pgQvhdX9/KRDSC8V4QCJBiE3LQPHUVdN
nWRixrcOpucMo6m9PPegjnicn/rBKdFZLfJqLHHm+TrHrNCsEQIDAQABMA0GCSqG
SIb3DQEBCwUAA4IBAQBGwlNnDh2UaZphkEf70MPhySFVnTnLSxUFuwuWaDu8l7YP
zBMeJxcNk3HNiXPeba03GQBj+JqGAwDALJLityGeGEzlESfv/BsgQOONt+lAJUjs
b7+vr2e5REE/dpJZ1kQRQC##########################################
np+GstsdWjIWbL6L6VoqU18qLO5b0k8OoEMsP3akUTcj0w8JwD5V5iLqDhnv1aXK
kntkd/QmVCY6zlzH/dnTh8RNO2CfRtB1GEzNnkJB</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
var testData = Encoding.UTF8.GetBytes(strText);
using (var rsa = new RSACryptoServiceProvider(1024))
{
try
{
rsa.FromXmlString(publicKey);
byte[] data = Encoding.UTF8.GetBytes(strText);
byte[] cipherText = rsa.Encrypt(data,true);
var base64Encrypted = Convert.ToBase64String(cipherText);
return base64Encrypted;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
}
}
Here is my public key. I am using an RSA certificate. I am passing the certificate key to the module tag here is my key. I think I might be using it wrong.
-----BEGIN CERTIFICATE-----
MIIDSjCCAjKgAwIBAgIEWrJUKTANBgkqhkiG9w0BAQsFADBmMQswCQYDVQQGEwJE
RTEPMA0GA1UECAwGQmF5ZXJuMQ8wDQYDVQQHDAZNdW5pY2gxDzANBgNVBAoMBkxl
eGNvbTEkMCIGA1UEAwwbQWdyb3BhcnRzX0RNU19CYXNrZXRfVXBsb2FkMCAXDTE4
MDMyMTEyNDYzM1oY################################################
A1UECAwG########################################################
################################################################
WaOa0parvIrMk9/#################################################
NCIeGu+epwg8oUCr6Wd0BNATNjt8Tk64pgQvhdX9/KRDSC8V4QCJBiE3LQPHUVdN
nWRixrcOpucMo6m9PPegjnicn/rBKdFZLfJqLHHm+TrHrNCsEQIDAQABMA0GCSqG
SIb3DQEBCwUAA4IBAQBGwlNnDh2UaZphkEf70MPhySFVnTnLSxUFuwuWaDu8l7YP
zBMeJxcNk3HNiXPeba03GQBj+JqGAwDALJLityGeGEzlESfv/BsgQOONt+lAJUjs
b7+vr2e5REE/dpJZ1kQRQC##########################################
np+GstsdWjIWbL6L6VoqU18qLO5b0k8OoEMsP3akUTcj0w8JwD5V5iLqDhnv1aXK
kntkd/QmVCY6zlzH/dnTh8RNO2CfRtB1GEzNnkJB
-----END CERTIFICATE-----
Any help would be highly appreciated. The encryption through this code is not working. But when I used the mentioned link above and pass this key it worked fine.
The answer to my question is here. I solved my problem and I am posting it because maybe someone in the future will have the same issue I am facing and what mistake I did to achieve my requirements.
Findings
I found during my research there is a difference between Public Key and Certificate. I miss understood the terminology I was passing a certificate instead of passing Public Key for encryption. So one of the community members #Topaco basically redirected me to the correct path which helps me to solve my problem. There are steps involved if you have a public key then you can achieve encryption but if you have a certificate then first you need to get the public key by using the method GetRSAPublicKey. When you got your public key in XML form then you pass it to encrypt method to get your result.
Here is the coding
Program.cs
var x509 = new X509Certificate2(File.ReadAllBytes(#"D:\xyz.cer"));
string xml = x509.GetRSAPublicKey().ToXmlString(false);
var result = EncryptUtil.Encryption("start01!", xml);
Utility Class
public static string Encryption(string strText, string publicKey)
{
using (var rsa = new RSACryptoServiceProvider(1024))
{
try
{
rsa.FromXmlString(publicKey);
byte[] data = Encoding.UTF8.GetBytes(strText);
byte[] cipherText = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
var base64Encrypted = Convert.ToBase64String(cipherText);
return base64Encrypted;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
So you can achieve encryption using the above code you need to pass RSAEncryptionPadding.Pkcs1 for encryption.
#happycoding #keephelping

Walmart Affiliate Signature C# .Net

I am trying to create a sha256 signature using a RSA Private Key but I am getting a 401 "Could not authenticate in-request, auth signature : Signature verification failed: affil-product, version: 2.0.0, env: prod
I think the issue is to do whit how it get my .pem file. I have read the Microsoft documentation and the provided Walmart example. I am following this guide. I created a non password protected key pair and uploaded the public key to Walmart. I then added my consumer ID and key version to appsettings.json {"Settings": {"consumerID": "e2ca6a2f-56f2-4465-88b3-273573b1e0c9","keyVer": "4"}}.
I am then getting this data in program.cs via the following code.
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
// Get values from the config given their key and their target type.
Settings settings = config.GetRequiredSection("Settings").Get<Settings>();
I then instantiate Walmart affiliate object allowing us to use the methods needed to access and read Walmart api
WalMartAfilAPI wallMartAfilAPI = new WalMartAfilAPI();
From there I Create a RSACryptoServiceProvider object and import the .pem and export the parameter.
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
var rsaPem = File.ReadAllText("D:\\Users\\Adam\\source\\repos\\DealsBot\\DealsBot\\DealsBot\\wallmartAfill\\WM_IO_private_key.pem");
//now we instantiate the RSA object
var rsa = RSA.Create();
//replace the private key with our .pem
rsa.ImportFromPem(rsaPem);
//Export the key information to an RSAParameters object.
// You must pass true to export the private key for signing.
// However, you do not need to export the private key
// for verification.
RSAParameters Key = rsa.ExportParameters(true);
From here I get the time stamp and call methods from the Walmart Affiliate object.
//Get current im in unix epoch milliseconds
TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
var time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
Console.WriteLine(time);
byte[] conicData = wallMartAfilAPI.Canonicalize(settings.KeyVer, settings.ConsumerID, time);
byte[] signedData = wallMartAfilAPI.HashAndSignBytes(conicData, Key);
if (wallMartAfilAPI.VerifySignedHash(conicData, signedData, Key))
{
Console.WriteLine("The data was verified");
;
Console.WriteLine(Convert.ToBase64String(signedData));
}
else
{
Here is the WalMartAfilAPI class
namespace DealsBot.wallmartAfill
{
public class WalMartAfilAPI
{
public byte[] Canonicalize(string version, string consumerId, string timestamp)
{
ASCIIEncoding ByteConverter = new ASCIIEncoding();
// Follow after the java code, which just orders the keys/values.
StringBuilder keyBuilder = new StringBuilder();
StringBuilder valueBuilder = new StringBuilder();
SortedDictionary<string, string> dictionary = new SortedDictionary<string, string>() { { "WM_CONSUMER.ID", consumerId }, { "WM_CONSUMER.INTIMESTAMP", timestamp }, { "WM_SEC.KEY_VERSION", version } };
foreach (string key in dictionary.Keys)
{
keyBuilder.Append($"{key.Trim()};");
valueBuilder.AppendLine($"{dictionary[key].Trim()}");
}
string[] conHeader = { keyBuilder.ToString(), valueBuilder.ToString() };
byte[] originalData = ByteConverter.GetBytes(conHeader[1]);
return originalData;
}
public byte[] HashAndSignBytes(byte[] DataToSign, RSAParameters Key)
{
try
{
// Create a new instance of RSACryptoServiceProvider using the
// key from RSAParameters.
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
RSAalg.ImportParameters(Key);
// Hash and sign the data. Pass a new instance of SHA256
// to specify the hashing algorithm.
return RSAalg.SignData(DataToSign, SHA256.Create());
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
public bool VerifySignedHash(byte[] DataToVerify, byte[] SignedData, RSAParameters Key)
{
try
{
// Create a new instance of RSACryptoServiceProvider using the
// key from RSAParameters.
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();
RSAalg.ImportParameters(Key);
// Verify the data using the signature. Pass a new instance of SHA256
// to specify the hashing algorithm.
return RSAalg.VerifyData(DataToVerify, SHA256.Create(), SignedData);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return false;
}
}
}
}
As of today, auth signature code is available in Java (https://www.walmart.io/docs/affiliate/onboarding-guide)
The idea we provided sample code to help the customers to implement the logic at customer end by referring it
You can implement the logic in(C# .NET, Python, PHP or JS) in such a way that whenever your system invoking Walmart APIs, generate the signature on the fly and pass as input parameter
This is how all of customers implemented and consuming our APIs
Pls refer the below documentation for complete.
https://walmart.io/docs/affiliate/quick-start-guide
https://www.walmart.io/docs/affiliate/onboarding-guide
Regards,
Firdos
IO Support

Generate Bitcoin public/private key from Guid C#

I have a randomly generated 128 bit guid (cryptographically secure). How can I use this as a seed to generate a public and private key for Bitcoin, using C#? By seed, I mean that every time I use the same guid as input, it should result in the same public/private keys.
I have looked at NBitcoin, but don't understand how to pull it off.
You can directly create 32 random bytes to be your private key. Example below. But it is VERY important: these 32 bytes must be from cryptographically-secure pseudorandom generator. For example, if you use C# built-in Random class, anyone will be able to restore your private keys with regular computer. You need to be very careful if you plan to use this in real bitcoin network. I am not sure if Guid generation is cryptographically-secure.
static void Main(string[] args)
{
byte[] GetRawKey()
{
// private key=1 in this example
byte[] data = new byte[32];
data[^1] = 1;
return data;
}
var key = new Key(GetRawKey()); // private key
var pair = key.CreateKeyPair(); // key pair (pub+priv keys)
var addrP2pkh = key.GetAddress(ScriptPubKeyType.Legacy, Network.Main); // P2PKH address
var addrP2sh = key.GetAddress(ScriptPubKeyType.SegwitP2SH, Network.Main); // Segwit P2SH address
Console.WriteLine(addrP2pkh.ToString());
Console.WriteLine(addrP2sh.ToString());
}

Verification of ruby-generated RSA SHA256 signature fails in C#

I have the following code in ruby and C# to generate and verify RSA signature.
Ruby
Keys generation (in PEM format)
keys = OpenSSL::PKey::RSA.new 512
private_key = key.to_pem
public_key = key.public_key.to_pem
I store these keys in environment variables ENV["PRIVATE_KEY"] and ENV["PUBLIC_KEY"]
Generate signature
def generate_signature(token)
sign_hash = OpenSSL::Digest::SHA256.new
priv = OpenSSL::PKey::RSA.new(ENV["PRIVATE_KEY"])
signature = Base64.urlsafe_encode64(priv.sign(sign_hash, token))
signature.gsub!(/\n/, '')
end
Verify signature
def verify_signature(signature, token)
verify_hash = OpenSSL::Digest::SHA256.new
pub = OpenSSL::PKey::RSA.new(ENV["PUBLIC_KEY"])
pub.verify(verify_hash, Base64.urlsafe_decode64(signature), token)
end
given these methods, the following code returns true, so verification is succesful.
signature = generate_signature("string")
puts verify_signature(signature, "string")
C#
In C# I don't need to generate keys, I just need to verify signature, generated previously in ruby. Since System.Security.Cryptography doesn't work with PEM keys out of the box, I converted PEM key to XML format (using online converter)
Here is verification code, which returns false, so verification is unsuccesfull.
public const string publicKey = #"Public key in XML format";
public static bool Verify(string nonce, string signature)
{
RSACryptoServiceProvider RSAVerifier = new RSACryptoServiceProvider();
RSAVerifier.FromXmlString(publicKey);
signature = Base64Decode(signature);
byte[] SignatureBytes = Encoding.UTF8.GetBytes(signature);
byte[] VerifyFileData = Encoding.UTF8.GetBytes(nonce);
bool isValidSignature = RSAVerifier.VerifyData(VerifyFileData, CryptoConfig.MapNameToOID("SHA256"), SignatureBytes);
return isValidSignature;
}
Where Base64Decode is my custom method to replicate Base64.urlsafe_decode64 in ruby
public static string Base64Decode(string base64EncodedData)
{
byte[] base64EncodedBytes = Convert.FromBase64String(base64EncodedData.Replace('-', '+').Replace('_', '/'));
return Encoding.UTF8.GetString(base64EncodedBytes);
}

Using RSA with my private key by C#

I'm provided a private key (a string). I have to generate a public key by that private key to encrypt data.
I don't know how to do. Please help me. Thank you.
Simply by having the private key you can not generate a public key.
Private and public keys are generated in pair and should be provided to you for encrypting data.
However you still can sign data using private key alone.
var keypair = "Your keypair in xml format";
using (var rsa = new RSACryptoServiceProvider()) {
rsa.FromXmlString(keypair);
var publicKeyInXmlFormat = rsa.ToXmlString(false);
}

Categories

Resources