I generate an AsymmetricCipherKeyPair as follows:
string curveName = "P-521";
X9ECParameters ecP = NistNamedCurves.GetByName(curveName);
ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDH");
g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));
AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();
My intention was to extract the public and private keys and then rebuild the keys later. I first extracted the keys as follows:
byte[] privateKey = ((ECPrivateKeyParameters)aKeyPair.Private).D.ToByteArray();
byte[] publicKey = ((ECPublicKeyParameters)aKeyPair.Public).Q.GetEncoded();
How do I recreate the public and private key parameters so that I can use them? In this example, I do recreate the private key and then sign the data byte array.
public static byte[] SignData(byte[] data, byte[] privateKey)
{
string curveName = "P-521";
X9ECParameters ecP = NistNamedCurves.GetByName(curveName);
ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
BigInteger biPrivateKey = new BigInteger(privateKey);
ECPrivateKeyParameters keyParameters = new ECPrivateKeyParameters(biPrivateKey, ecSpec);
signer.Init(true, keyParameters);
signer.BlockUpdate(data, 0, data.Length);
return signer.GenerateSignature();
}
Although it feels like a real hack, it works just fine. How can I do this with the Public Key? I set the variable xxx to (ECPublicKeyParameters)aKeyPair.Public and I can use the code below to verify the signature. Note that I could use xxx directly, but the point is to serialize xxx out and then back in, so, this code actually does convert the xxx variable and creates a new one, which is stored in xx. I then use xx to verify (which shows that I can round trip the key).
var xx = PublicKeyFactory.CreateKey(Org.BouncyCastle.X509.SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(xxx).GetDerEncoded());
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
signer.Init(false, xx);
signer.BlockUpdate(data, 0, data.Length);
return signer.VerifySignature(signature);
I had hoped that I could create the key (xx) from Q.GetEncoded() similar to how I did it for the private key.
Is there a better way to rebuild the private key? also using an ASN.1 encoding? If so, perhaps I should use that instead.
I can do this as follows:
string curveName = "P-521";
X9ECParameters ecP = NistNamedCurves.GetByName(curveName);
FpCurve c = (FpCurve)ecP.Curve;
ECFieldElement x = new FpFieldElement(c.Q, xxx.Q.X.ToBigInteger());
ECFieldElement y = new FpFieldElement(c.Q, xxx.Q.Y.ToBigInteger());
ECPoint q = new FpPoint(c, x, y);
ECPublicKeyParameters xxpk = new ECPublicKeyParameters("ECDH", q, SecObjectIdentifiers.SecP521r1);
Then, I can use xxpk to verify the signature.
Disclaimer: I do not claim that this is the best way to do this, just that it works!
Related
First off, I'm still new to crypto/signing so bear with any misuse of terms please.
I need to create a signature in C# that is getting verified by a Python library. In Python, it's a simple chunk of code to decode/verify the signature:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
public_key.verify(signature, payload_contents,
padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH,
), hashes.SHA256(), )
My current C# code looks like this:
private static string CreateSignature(byte[] data, string privateKeyFileLocation)
{
var cert = new X509Certificate2(privateKeyFileLocation);
byte[] signedBytes;
using (var rsa = cert.GetRSAPrivateKey())
{
signedBytes = rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
}
var finalString = Convert.ToBase64String(signedBytes);
return finalString;
}
However, the signature is failing the verification check in the Python code. It looks like PSS padding in the .Net libraries defaults to using MGF1. However, I believe I'm having issues due to the mask generation function (MGF1) using a 256-bit hash in the Python code, but defaulting to SHA1 in C#. I've waded through the .Net C# documentation and it looks like there is no way to override this. I looked into Bouncy Castle's C# documentation and am just having trouble finding any kind of similar example of how to set padding with custom params. Does anyone have experience in this area and can lend a few hints?
Just for anyone else dealing with this. This is the code I ended up with.
private static string GenerateSignatureForData(string data, string privateKeyFileLocation)
{
var cert = new X509Certificate2(privateKeyFileLocation, "12345", X509KeyStorageFlags.Exportable);
var bcCert = TransformRSAPrivateKey(cert.PrivateKey);
var keyLen = (int)Math.Ceiling((cert.GetRSAPrivateKey().KeySize - 1) / 8.0);
byte[] signedBytes = CreateSignature(Encoding.ASCII.GetBytes(data), bcCert, keyLen);
return Convert.ToBase64String(signedBytes);
}
private static AsymmetricKeyParameter TransformRSAPrivateKey(AsymmetricAlgorithm privateKey)
{
RSACryptoServiceProvider prov = privateKey as RSACryptoServiceProvider;
RSAParameters parameters = prov.ExportParameters(true);
return new RsaPrivateCrtKeyParameters(
new BigInteger(1, parameters.Modulus),
new BigInteger(1, parameters.Exponent),
new BigInteger(1, parameters.D),
new BigInteger(1, parameters.P),
new BigInteger(1, parameters.Q),
new BigInteger(1, parameters.DP),
new BigInteger(1, parameters.DQ),
new BigInteger(1, parameters.InverseQ));
}
private static byte[] CreateSignature(byte[] data, AsymmetricKeyParameter privateKey, int keyLength)
{
var digest = new Sha256Digest();
var saltLength = keyLength - digest.GetDigestSize() - 2;
PssSigner signer = new PssSigner(new RsaEngine(), new Sha256Digest(), digest, saltLength);
signer.Init(true, new ParametersWithRandom((RsaPrivateCrtKeyParameters)privateKey));
signer.BlockUpdate(data, 0, data.Length);
return signer.GenerateSignature();
}
There's some extra in there because the salt length also had to be calculated. I had to look at the source code for the crypto library to calculate the salt MAX_LENGTH indicated in the python code here:
salt_length=padding.PSS.MAX_LENGTH
Here is strictly the code required to do that:
var cert = new X509Certificate2(privateKeyFileLocation, "12345", X509KeyStorageFlags.Exportable);
var bcCert = TransformRSAPrivateKey(cert.PrivateKey);
var keyLen = (int)Math.Ceiling((cert.GetRSAPrivateKey().KeySize - 1) / 8.0);
var digest = new Sha256Digest();
var saltLength = keyLength - digest.GetDigestSize() - 2;
Similarly, converting the .Net crypto lib AsymmetricAlgorithm to a Bouncy Castle AsymmetricKeyParameter required the conversion function TransformRSAPrivateKey seen above.
There is tweetnacl-sealedbox-js for node.js
For example we can encrypt some data
const key = crypto.pseudoRandomBytes(32);
const publicKey = 'ed9f2af89336b2ff5960634fafb401ca36644cad61cb6a1daafdda0c74ef4636';
const encryptedKey = seal(key, Buffer.from(publicKey, 'hex'));
But is there similar library for C# ? I'm trying to use libsodium-net but am not completely sure that this is correct
For example
byte[] randKey = new byte[32];
Random.NextBytes(randKey);
string publicKey = "ed9f2af89336b2ff5960634fafb401ca36644cad61cb6a1daafdda0c74ef4636";
byte[] encryptedKey = SealedPublicKeyBox.Create(randKey, HexToByte(publicKey));
public static byte [] HexToByte(string hexStr)
{
byte[] bArray = new byte[hexStr.Length / 2];
for (int i = 0; i < (hexStr.Length / 2); i++)
{
byte firstNibble = Byte.Parse(hexStr.Substring((2 * i), 1),
System.Globalization.NumberStyles.HexNumber); // [x,y)
byte secondNibble = Byte.Parse(hexStr.Substring((2 * i) + 1, 1),
System.Globalization.NumberStyles.HexNumber);
int finalByte = (secondNibble) | (firstNibble << 4);
bArray[i] = (byte)finalByte;
}
return bArray;
}
Does anybody know can the owner of private key decrypt both messages? or c# code is not the same action?
SO I make some tests:
run var keyPair = tweetnacl.box.keyPair() at node.js and convert to base64 strings public key and secret key.
var pubKey = Buffer.from('Uv4bICdcUlIO+Z9YsLLg9EGaLPy/M7oTBVZJn2B7XhU=', 'base64');
var secKey = Buffer.from('fEAUUQ+axuD3NkOr+a59ZtsVurZPTa4Ee8ULoNr3WS0=', 'base64');
try to encrypt message via c# and libsodium-net like that:
string mes = "i want to believe";
string pKey = "Uv4bICdcUlIO+Z9YsLLg9EGaLPy/M7oTBVZJn2B7XhU=";
byte [] enc = Sodium.SealedPublicKeyBox.Create(mes, Convert.FromBase64String(pKey));
return Convert.ToBase64String(enc);
and try to decrypt message via node.js
var msg = Buffer.from('uW+5ecQhzKKx++uRYcbCu2nUVNIqToWTSjVB7UmdDCeJn9Buf3UWFu5kRfIGIxMJYdVeTFijdvJhlHR0VBd5HnE=', 'base64');
var result = sealedbox.open(msg, pubKey, secKey);
console.log(Buffer.from(result).toString());
and got my message in log.
so I found out that these libraries are mutually compatible.
the next unit test export a privatekey and save it in bytes arrays using the rsa instance then encrypt the "hi" message, all is fine here, but the problem occur when It make rsa2 instance and import the previous privatekey in RSAParameter, then message can be decrypt after import privatekey, but It throw exception when you try to export privatekey of rsa2.
Please could you tell me why It can't extract Imported Private key
[TestMethod]
public void TestRsa()
{
var rsa = new RSACng(2048);
///Export private key to arrays
var rsaParam = rsa.ExportParameters(true);
byte[] yQ = new byte[rsaParam.Q.Length];
byte[] yP = new byte[rsaParam.P.Length];
byte[] yInverseQ = new byte[rsaParam.InverseQ.Length];
byte[] yDP = new byte[rsaParam.DP.Length];
byte[] yDQ = new byte[rsaParam.DQ.Length];
//Public Part Key
byte[] yPm = new byte[rsaParam.Modulus.Length];
byte[] yPe = new byte[rsaParam.Exponent.Length];
byte[] yD = new byte[rsaParam.D.Length];
rsaParam.Q.CopyTo(yQ, 0);
rsaParam.P.CopyTo(yP, 0);
rsaParam.InverseQ.CopyTo(yInverseQ, 0);
rsaParam.DP.CopyTo(yDP, 0);
rsaParam.DQ.CopyTo(yDQ, 0);
rsaParam.Modulus.CopyTo(yPm, 0);
rsaParam.Exponent.CopyTo(yPe, 0);
rsaParam.D.CopyTo(yD, 0);
var encrypt = rsa.Encrypt(Encoding.UTF8.GetBytes("hi"), RSAEncryptionPadding.Pkcs1);
///Importing private key in another instance of RSACng
var rsa2 = new RSACng(2048);
RSAParameters rsaParameters = new RSAParameters()
{
Q = yQ,
P = yP,
InverseQ = yInverseQ,
DP = yDP,
D = yD,
DQ = yDQ,
Exponent = yPe,
Modulus = yPm
};
rsa2.ImportParameters(rsaParameters);
var decryptData = rsa2.Decrypt(encrypt, RSAEncryptionPadding.Pkcs1);
Assert.AreEqual(Encoding.UTF8.GetString(decryptData), "hi");
rsa2.ExportParameters(true);///How can I prevent exception here
}
Thanks all!
In .NET Core the RSACng object should be in an exportable state when you use ImportParameters, and it should be the case in .NET Framework 4.7.2 as well.
You can put into an exportable state as long as you change the export policy before using the key (by trying to call Export or doing a sign/decrypt/encrypt/verify operation). For example, this works:
using (RSA rsa1 = new RSACng(2048))
using (RSACng rsa2 = new RSACng())
{
rsa2.ImportParameters(rsa1.ExportParameters(true));
rsa2.Key.SetProperty(
new CngProperty(
"Export Policy",
BitConverter.GetBytes((int)CngExportPolicies.AllowPlaintextExport),
CngPropertyOptions.Persist));
RSAParameters params2 = rsa2.ExportParameters(true);
Console.WriteLine(params2.D.Length);
}
Using the NCRYPT_EXPORT_POLICY_PROPERTY described at https://msdn.microsoft.com/en-us/library/windows/desktop/aa376242(v=vs.85).aspx.
How can I verify signature for open PGP using BouncyCastle?
I am using C#
I have pulic key http://itransact.com/support/toolkit/html-connection/pgp.php
I am using BouncyCastle as open pgp library
I have signature that I recieve in query string.
According to instruction (http://itransact.com/downloads/PCFullDocument-4.4.pdf p.145) algorithm is RSA.
I checked a lot of resource but no success. As I understood I need to pass public key and signature to some Verify method.
It is also not clear if I have to convert given public key in string format to some appropriate public key object. If I have to what is the type? I have tried to convert it to RsaKeyParameters but got error message about inappropriate block on public key.
At the moment I have the following code
private bool VerifyWithPublicKey(string data, byte[] sig)
{
RSACryptoServiceProvider rsa;
using (var keyreader = new StringReader(publicKey))
{
var pemReader = new PemReader(keyreader);
var y = (RsaKeyParameters)pemReader.ReadObject();
rsa = (RSACryptoServiceProvider)RSA.Create();
var rsaParameters = new RSAParameters();
rsaParameters.Modulus = y.Modulus.ToByteArray();
rsaParameters.Exponent = y.Exponent.ToByteArray();
rsa.ImportParameters(rsaParameters);
// compute sha1 hash of the data
var sha = new SHA1CryptoServiceProvider();
byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(data));
// This always returns false
return rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), sig);
}
Using RSA is not your case. You need
Define public key
Convert public ket into PgPPublicKey
Get PgpSignature object
Verify signature
To verify signature you will need original data that was signed.
public class iTransactVerifier
{
private const string PublicKey = #"-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: 4.5
mQCNAjZu
-----END PGP PUBLIC KEY BLOCK-----";
public static bool Verify(string signature, string data)
{
var inputStream = ConvertStringToStream(signature);
PgpPublicKey publicKey = ReadPublicKeyFromString();
var stream = PgpUtilities.GetDecoderStream(inputStream);
PgpObjectFactory pgpFact = new PgpObjectFactory(stream);
PgpSignatureList sList = pgpFact.NextPgpObject() as PgpSignatureList;
if (sList == null)
{
throw new InvalidOperationException("PgpObjectFactory could not create signature list");
}
PgpSignature firstSig = sList[0];
firstSig.InitVerify(publicKey);
firstSig.Update(Encoding.UTF8.GetBytes(data));
var verified = firstSig.Verify();
return verified;
}
....
private static PgpPublicKey ReadPublicKeyFromString()
{
var varstream = ConvertStringToStream(PublicKey);
var stream = PgpUtilities.GetDecoderStream(varstream);
PgpObjectFactory pgpFact = new PgpObjectFactory(stream);
var keyRing = (PgpPublicKeyRing)pgpFact.NextPgpObject();
return keyRing.GetPublicKey();
}
}
I want functions for import/export PEM/DER strings in C#. I'm using RSA on python and C# but i had no solution who worked fine beetween both language.
After many many tries and many research, i finally found an solution who working for read PEM public key. The following code works :
// pubkey is the PEM file without header/footer and encoded base64
Asn1Object obj = Asn1Object.FromByteArray(pubkey_bytes);
DerSequence publicKeySequence = (DerSequence)obj;
DerSequence publicKey = (DerSequence)Asn1Object.FromByteArray(publicKeySequence.GetEncoded());
DerInteger modulus = (DerInteger)publicKey[0];
DerInteger exponent = (DerInteger)publicKey[1];
RsaKeyParameters keyParameters = new RsaKeyParameters(false, modulus.PositiveValue, exponent.PositiveValue);
RSAParameters parameters = DotNetUtilities.ToRSAParameters(keyParameters);
this code is inspired of a solution i found on StackOverflow. But when i'm trying to use the same solution for private key i have an exception "Spécified size too small". This error seems appears on the "InverseQ" line. Below the code i'm using :
// Private key encode base64 without header/footer
Asn1Object obj = Asn1Object.FromByteArray(privkey_bytes);
DerSequence privateKeySequence = (DerSequence)obj;
DerSequence privateKey = (DerSequence)Asn1Object.FromByteArray(privateKeySequence.GetEncoded());
DerInteger M = (DerInteger)privateKey[1];
DerInteger E = (DerInteger)privateKey[2];
DerInteger D = (DerInteger)privateKey[3];
DerInteger P = (DerInteger)privateKey[4];
DerInteger Q = (DerInteger)privateKey[5];
DerInteger DP = (DerInteger)privateKey[6];
DerInteger DQ = (DerInteger)privateKey[7];
DerInteger IQ = (DerInteger)privateKey[8];
var keyParameters = new RsaPrivateCrtKeyParameters(M.PositiveValue,
E.PositiveValue, D.PositiveValue, P.PositiveValue, Q.PositiveValue,
DP.PositiveValue, DQ.PositiveValue, IQ.PositiveValue);
RSAParameters parameters = DotNetUtilities.ToRSAParameters(keyParameters); // Exception here !
I tried also this code from another StackOverflow post, for fix padding issues, but it's not my problem here :
RSAParameters parameters = new RSAParameters();
parameters.Modulus = M.PositiveValue.ToByteArrayUnsigned();
parameters.Exponent = E.PositiveValue.ToByteArrayUnsigned();
parameters.P = P.PositiveValue.ToByteArrayUnsigned();
parameters.Q = Q.PositiveValue.ToByteArrayUnsigned();Modulus.Length);
parameters.DP = ConvertRSAParametersField(DP.PositiveValue, parameters.P.Length);
parameters.DQ = ConvertRSAParametersField(DQ.PositiveValue, parameters.Q.Length);
parameters.InverseQ = ConvertRSAParametersField(IQ.PositiveValue, parameters.Q.Length);
public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey)
{
RSAParameters rp = new RSAParameters();
rp.Modulus = privKey.Modulus.ToByteArrayUnsigned();
rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned();
rp.P = privKey.P.ToByteArrayUnsigned();
rp.Q = privKey.Q.ToByteArrayUnsigned();
rp.D = ConvertRSAParametersField(privKey.Exponent, rp.Modulus.Length);
rp.DP = ConvertRSAParametersField(privKey.DP, rp.P.Length);
rp.DQ = ConvertRSAParametersField(privKey.DQ, rp.Q.Length);
rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length); // Exception HERE
return rp;
}
private static byte[] ConvertRSAParametersField(BigInteger n, int size)
{
byte[] bs = n.ToByteArrayUnsigned();
if (bs.Length == size)
return bs;
if (bs.Length > size) // HERE
throw new ArgumentException("Specified size too small", "size");
byte[] padded = new byte[size];
Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
return padded;
}
My private key is generated by python and i think it a normal key :
-----BEGIN RSA PRIVATE KEY-----
MIICYAIBAAKBgQCUkUk/vvyTI3begsdjz7eQVchjMTYMTyqt8HHHSXYXY2GrQCZS
VfBVxFLmx19brgMdLrKO93CjJWt+ACXAaLHmuGCsvNgGjCFqgg4XxM4Xamt9PeOc
F8HhMH7iS3OcgybQuu9GrekZB0yL2L9GVpyVrXpVlVHi4gBVjUr80e5LUwIDAQAB
AoGAGgK9wk1bxx8EZrya0BzD1J9QMB2jitApdr6MDQoNhNa/eM4IZ43oP/vZT9JE
Hbb/kJJmbKVhsQ6SHUNFO6qJA0FWYNqEA1xsTtat3RXAB/WCExxW9GwDG6pEXjK8
OrJFbKyIOhmqy3sBib9V76ROYsMi7Gioih8vtYKz8NFBiZECRQCmOHzCqEbsWJnK
5JUsUG8DyR3wg8mzi98m1qYGz3hsuBJMCW2M/QBSgyWGdDxExbQMcTb9lmTelq4W
sHbZLQ3FVxJsbwI9AOTP4ZCLDnzblroQjiUCW1vbVE6YnoO0YTb67Dj/g9CNOZpz
E0lJ3boUlg6lOEpDdwKxSswXhQU53OMJXQJFAKC+BaB0/Uk4EVnNHZkiG4lsp2Bd
AeR4wg8cCqiRYCK7Cy6u+1sZm4Mvwk05AMN88TYLEiO/mcJLswTMF9LDqAqLvoxP
AjxDmlPXo+4k37AZyzhkIN0jN5siGZ+D5DBw0RQoBv5ICOHDC0rgdW2IQ/rN2uzV
rDcmWYFy6WQI1j636ZUCRHWmzCi6ymkcUnqwlYXsjbZSVM7njOc3sJyVhaOgqs+o
1Zjbtpqq7DYEBHPFizh/nu6kf4lT3w5+vIKGs8r4k2IUMcJi
-----END RSA PRIVATE KEY-----
I have a doubt about the order of the parameters returned by "Asn1Object.FromByteArray()". I noticied the [0] was just a "0", that means empty for me. The length is 9 so it seems to be the good way, i'm just not sure about in which order they are returned. Tried to find some documentation but i found nothing.
Thanks in advance for people gonna help me
EDIT
First, i want to say my goal is to get a RSAParameters object.
As suggered by someone who deleted his post, i changed
rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length);
to
rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.P.Length);
but after doing it, i got an exception System.Security.Cryptography.CryptographicException who telling me "Incorrect data." on the line
var csp = new RSACryptoServiceProvider(); // my csp object is already defined somewhere else but it change nothing
csp.ImportParameters(parameters); // Exception here, he doesn't like my object who doesn't seems valid for him.
The real problem seems to be "why my object is rejected by RSACryptoServiceProvider.ImportParameters()