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.
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.
in .net core 3.1 I am using ImportPkcs8PrivateKey and ImportRSAPrivateKey for some RSA private Key import as per following function
private RSA RsaKeyAsPerContent()
{
//https://csfieldguide.org.nz/en/interactives/rsa-key-generator/
//https://travistidwell.com/jsencrypt/demo/
RSA rSA = RSA.Create();
string privateKeyContent = "...."
bool isPkcsprivateKey = privateKeyContent.Contains("BEGIN PRIVATE KEY");
if (isPkcsprivateKey)
{
var privateKey = privateKeyContent.Replace("-----BEGIN PRIVATE KEY-----", string.Empty).Replace("-----END PRIVATE KEY-----", string.Empty);
privateKey = privateKey.Replace(Environment.NewLine, string.Empty);
var privateKeyBytes = Convert.FromBase64String(privateKey);
rSA.ImportPkcs8PrivateKey(privateKeyBytes, out int _);
}
else
{
var privateKey = privateKeyContent.Replace("-----BEGIN RSA PRIVATE KEY-----", string.Empty).Replace("-----END RSA PRIVATE KEY-----", string.Empty);
privateKey = privateKey.Replace(Environment.NewLine, string.Empty);
var privateKeyBytes = Convert.FromBase64String(privateKey);
rSA.ImportRSAPrivateKey(privateKeyBytes, out int _);
}
return rSA;
}
now I need same import functionality in traditional .net framework version 4.6/4.7 but it is not available
Any idea how can i do it in .net framework
You can try the following. It has been tested on .net framework 4.8 and it uses a 3rd party package "BouncyCastle.Crypto".
public static RSACryptoServiceProvider ImportPrivateKey(string pem) {
PemReader pr = new PemReader(new StringReader(pem));
AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
RSAParameters rsaParams =
DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)KeyPair.Private);
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();// cspParams);
csp.ImportParameters(rsaParams);
return csp;
}
You can refer to https://gist.github.com/ststeiger/f4b29a140b1e3fd618679f89b7f3ff4a for more details.
Following is been used in .net framework 4.6
private static RSA RsaKeyAsPerContent()
{
RSA rSA = RSA.Create();
string privateKeyFromConfig = ConfigurationManager.AppSettings["privateKey"];
rSA.ImportParameters(ImportPrivateKey(privateKeyFromConfig));
return rSA;
}
public static RSAParameters ImportPrivateKey(string pem)
{
PemReader pr = new PemReader(new StringReader(pem));
RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters)pr.ReadObject();
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);
return rp;
}
private static byte[] ConvertRSAParametersField(BigInteger n, int size)
{
byte[] bs = n.ToByteArrayUnsigned();
if (bs.Length == size)
return bs;
if (bs.Length > size)
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;
}
We need to take Modulus and exponent from RSA keys. I have created my pubilc key using following methodology. Please let me know how can we take modulus and exponent part from it. I have already read this post.
NSData* tag = [#"com.x.x.x" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* attributes =
#{ (id)kSecAttrKeyType: (id)kSecAttrKeyTypeRSA,
(id)kSecAttrKeySizeInBits: #1024,
(id)kSecPrivateKeyAttrs:
#{ (id)kSecAttrIsPermanent: #YES,
(id)kSecAttrApplicationTag: tag,
},
};
CFErrorRef error = NULL;
SecKeyRef privateKey = SecKeyCreateRandomKey((__bridge CFDictionaryRef)attributes,
&error);
if (!privateKey) {
NSError *err = CFBridgingRelease(error);
// Handle the error. . .
}
SecKeyRef publicKey = SecKeyCopyPublicKey(privateKey);
// Now I want modulus and exponent form this publicKey
EDITED :-
I have also send base64 string to server but there we are facing quite a issue to find public key ref from base64 string. if someone has done it in c#, you can also help us with this
c# code snippet
const string pKey = "-----key-----"
byte[] publicKeyBytes = Convert.FromBase64String(pKey);
var stream = new MemoryStream(publicKeyBytes);
Asn1Object asn1Object = Asn1Object.FromStream(stream);
Now we need public key component which we are unable to parse. Any help would be great
On C# you can achieve the encryption using this way,
const string publicKey = "MIGJAoGBAMIt95f4xaP7vYV/+Hdyb4DK0oKvw495PrRYG3nsYgVP7zlBE/rTN6Nmt69W9d0nGefuRlJFIr9TA8vlJmqTus6uXEasBuEjzH7vM7HQeAK6i8qEbVy0T+Uuq+16yy059NL7i/VWljVE6rqTntDUELmbIwNBwj6oBuL1z3SnFoMjAgMBAAE="; //generated on iOS
byte[] publicKeyBytes = Convert.FromBase64String(pKey);
var stream = new MemoryStream(publicKeyBytes);
Asn1Object asn1Object = Asn1Object.FromStream(stream);
Asn1Encodable asn1Sequence = asn1Object;
AlgorithmIdentifier algorithmIdentifier = new
AlgorithmIdentifier(PkcsObjectIdentifiers.IdRsaesOaep);
SubjectPublicKeyInfo subjectPublicKeyInfo = new
SubjectPublicKeyInfo(algorithmIdentifier, asn1Sequence);
AsymmetricKeyParameter asymmetricKeyParameter2 =
PublicKeyFactory.CreateKey(subjectPublicKeyInfo);
RsaKeyParameters rsaKeyParameters =
(RsaKeyParameters)asymmetricKeyParameter2;
RSAParameters rsaParameters = new RSAParameters();
rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
string test = "John snow is the true king";
byte[] encbyte = rsa.Encrypt(Encoding.UTF8.GetBytes(test), RSAEncryptionPadding.Pkcs1);
string encrt = Convert.ToBase64String(encbyte);
The problem is the following:
I generate the key in Android (Xamarin.Droid):
public IPublicKey CreateKey(string keyID)
{
/*KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
keyPairGenerator.initialize(
new KeyGenParameterSpec.Builder(
"key1",
KeyProperties.PURPOSE_SIGN)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS)
.build());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Signature signature = Signature.getInstance("SHA256withRSA/PSS");
signature.initSign(keyPair.getPrivate());
// The key pair can also be obtained from the Android Keystore any time as follows:
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
PrivateKey privateKey = (PrivateKey)keyStore.getKey("key1", null);
PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();*/
//App.Current.MainPage.DisplayAlert("Info", "Creating a new key pair", "Ok");
// UTILIZANDO RSA
KeyPairGenerator kpg =
KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KEYSTORE_NAME);
kpg.Initialize(
new KeyGenParameterSpec.Builder(keyID,
KeyStorePurpose.Sign)
.SetSignaturePaddings(KeyProperties.SignaturePaddingRsaPss)
.SetDigests(KeyProperties.DigestSha1)
.Build()
);
KeyPair keyPair = kpg.GenerateKeyPair();
Log.Debug(TAG, "New key created for fingerprint authentication");
return keyPair.Public;
}
Then i generate a signature:
KeyStore.PrivateKeyEntry PKentry =
(KeyStore.PrivateKeyEntry)_keystore.GetEntry(keyID, null);
IPublicKey pk = (IPublicKey)PKentry.Certificate.PublicKey;
//this.pk = pk;
privKey = PKentry.PrivateKey;
//cipher.Init(Cipher.EncryptMode, privKey);
//byte[] output = cipher.DoFinal(Encoding.UTF8.GetBytes(input));
//String s = new string(cipher.DoFinal(input));
// signature
Signature sig = Signature.GetInstance("SHA1withRSA/PSS");
sig.InitSign(privKey);
byte[] inputDataToSign = Encoding.UTF8.GetBytes(input);
sig.Update(inputDataToSign);
byte[] signatureBytes = sig.Sign();
And i send the key and the signature to a ASP.net wep API 2 server.
Client side response generation:
RegistrationResponse registrationResponse = new RegistrationResponse();
string fcparams = Utils.Base64Encode(JsonConvert.SerializeObject(finalChallengeParams));
registrationResponse.fcParams = fcparams;
byte[] signedData = sign(fcparams, registrationRequest.username, facetID);
registrationResponse.signedData = signedData;
registrationResponse.Base64key = convertPublicKeyToString(publicKey);
...
...
private string convertPublicKeyToString(IPublicKey publicKey)
{
string publicKeyString = Base64.EncodeToString(publicKey.GetEncoded(), 0);
return publicKeyString;
}
I send it using Refit Nugget.
And this is the code i use when i receive the HTTPRequest on server side:
[Route("regResponse/")]
[HttpPost]
public IHttpActionResult ProcessClientRegistrationResponse([FromBody] RegistrationResponse registrationResponse)
{
//byte[] publicKeyBytes = Convert.FromBase64String(registrationResponse.Base64key);
byte[] publicKeyBytes = registrationResponse.Base64key;
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKeyBytes);
RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
RSAParameters rsaParameters = new RSAParameters();
rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
/*****/
string alg = rsa.SignatureAlgorithm;
byte[] signedData = registrationResponse.signedData;
byte[] fcParamsBytes = Encoding.UTF8.GetBytes(registrationResponse.fcParams);
RSACng rsaCng = new RSACng();
rsaCng.ImportParameters(rsaParameters);
SHA1Managed hash = new SHA1Managed();
byte[] hashedData;
hashedData = hash.ComputeHash(signedData);
/*********/
bool rsaCngDataOk1 = rsaCng.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
bool rsaCngDataOk2 = rsaCng.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
bool rsaCngDataOk3 = rsaCng.VerifyData(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
bool rsaCngDataOk4 = rsaCng.VerifyData(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
bool rsaCngHashOk1 = rsaCng.VerifyHash(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
bool dataOK1 = rsa.VerifyData(fcParamsBytes, new SHA1CryptoServiceProvider(), signedData);
bool dataOk2 = rsa.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
bool hashOk = rsa.VerifyHash(hashedData, CryptoConfig.MapNameToOID("SHA1"), signedData);
return Ok(true);
}
EVERY bool is wrong. I think the problem is clearly on the public key.
The questions are,
does the method publickey.encode() do what i think? I think it converts my public key to a byte[] representation (source: Android developer Key Info)
do i convert the received byte[] representation of the key to a correct RSA key?
Is there any problem on algorithms? I don't think so but we never know...
I don't find the solution. I searched for ways to import public keys from strings in .net or c# and for ways to export Android Public key to string or byte[] but there's no much help for this concrete questions...
#James K Polk gave me the solution.
Apparently C# doesn't work well with PSS padding. I just had to change it to PKCS1. And i changed to digest algorithm too to SHA512.
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!