Pasargad payment gateway sign method in nodejs - c#

Iran Pasargad bank requires to sign payment gateway request to be signed using RSA private key, following C# code snippet is provided by the bank and it's working, but I cant get it work using NodeJS.
public string GetSign(string data)
{
var cs = new CspParameters { KeyContainerName = "PaymentTest" };
var rsa = new RSACryptoServiceProvider(cs) { PersistKeyInCsp = false };
rsa.Clear();
rsa = new RSACryptoServiceProvider();
rsa.FromXmlString("<RSAKeyValue>Modulus>...</RSAKeyValue>");
byte[] signMain = rsa.SignData(Encoding.UTF8.GetBytes(data), new
SHA1CryptoServiceProvider());
string sign = Convert.ToBase64String(signMain);
return sign;
}

Finally I solved my problem using following code, Hope it could help others:
function getSign(data) {
const pemKey = `-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
`;
const crypto = require("crypto");
const signature = crypto.sign("sha1", Buffer.from(JSON.stringify(data)), { key: pemKey });
return signature.toString("base64");
}

Related

How to write RSA encrypt function in C#

I have following nodejs code to encrypt RSA:
const encryptWithRSA = (PublicKey, selData) => {
let encrypted = crypto.publicEncrypt(
{
key: -----BEGIN PUBLIC KEY-----\n${PublicKey}\n-----END PUBLIC KEY-----,
padding: crypto.constants.RSA_PKCS1_PADDING,
},
Buffer.from(selData)
);
return encrypted.toString("base64");
};
Then I tried to convert this code block to C# :
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
public static string Encrypt(string publickey, string data)
{
string key = publickey;
Asn1Object obj = Asn1Object.FromByteArray(Convert.FromBase64String(key));
DerSequence publicKeySequence = (DerSequence)obj;
DerBitString encodedPublicKey = (DerBitString)publicKeySequence[1];
DerSequence publicKey = (DerSequence)Asn1Object.FromByteArray(encodedPublicKey.GetBytes());
DerInteger modulus = (DerInteger)publicKey[0];
DerInteger exponent = (DerInteger)publicKey[1];
RsaKeyParameters keyParameters = new RsaKeyParameters(false, modulus.PositiveValue, exponent.PositiveValue);
RSAParameters parameters = DotNetUtilities.ToRSAParameters(keyParameters);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(parameters);
byte[] dataToEncrypt = Encoding.UTF8.GetBytes(data);
byte[] encryptedData = rsa.Encrypt(dataToEncrypt, RSAEncryptionPadding.Pkcs1);
return Convert.ToBase64String(encryptedData);
}
Two code return 2 different results. Anyone can show me what wrong? Thanks!

Cannot decrypt C# encrypted message using node-rsa npm

I've got a server written in node.js that I want to receive encrypted messages from a C# app. I tried to implement RSA firstly for this task, but with no avail, because I wasn't able to decrypt the message after being encrypted by the C# app using the keys generated by the server.
I've tried using the node-rsa npm for generating the keys on the server side and got this error when trying to decrypt the messages
"Error during decryption (probably incorrect key). Original error:
Error: Incorrect data or key".
I've also tried the crypto module for decrypting, but received this error instead
"error:0406506C:rsa routines:rsa_ossl_private_decrypt:data greater
than mod len".
The C# app is a console app as it is merely used for testing the encryption, which uses the RSAServiceProvider for importing the keys generated by the server(which are stored in the pem format), encrypting the message(or the key, if I am going to implement AES as well) and then sending it back to the server by writing it in a file.
This is the rsa-wrapper.js file which contains the rsa implementation:
const NodeRSA = require('node-rsa');
const fs = require('fs');
var key;
var generate = function () {
key = new NodeRSA();
key.generateKeyPair(2048, 65537);
fs.writeFileSync('./keys/public-key.pem', key.exportKey('pkcs8-public-pem'));
};
var encrypt = function (message) {
let encrypted = key.encrypt(message, 'base64');
return encrypted;
};
var decrypt = function (cipherText) {
let decrypted = key.decrypt(cipherText, 'utf8');
return decrypted;
}
module.exports.generate = generate;
module.exports.test = test;
module.exports.encrypt = encrypt;
module.exports.decrypt = decrypt;
This is the the app.js file which simply contains the GET functions for testing the encryption:
const express = require('express');
const rsaWrapper = require('./components/rsa-wrapper.js');
const app = express();
const fs = require('fs');
app.listen(3000);
app.get('/', function(req, res) {
console.log('Working');
res.render('index.ejs');
});
app.get('/generate', function(req, res) {
rsaWrapper.generate();
console.log('The keys have been generated successfully.');
res.render('index.ejs');
});
app.get('/decrypt', function(req, res) {
fs.readFile('./cipher-text.txt', (err, data) => {
if (err) throw err;
console.log('The original message is:' + rsaWrapper.decrypt(data));
});
res.render('index.ejs');
});
This is the console app written in C# for encrypting the message using the public key generated by the server:
static void Main(string[] args) {
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters rsaParam = rsa.ExportParameters(false);
String publicKey = File.ReadAllText(#"D:\NodeProjects\Test project\keys\public-key.pem").Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "");
publicKey = publicKey.Replace("\n", String.Empty);
publicKey = publicKey.Replace("\r", String.Empty);
publicKey = publicKey.Replace("\t", String.Empty);
rsaParam.Modulus = Convert.FromBase64String(publicKey);
byte[] intBytes = BitConverter.GetBytes(65537);
if (BitConverter.IsLittleEndian)
Array.Reverse(intBytes);
rsaParam.Exponent = intBytes;
rsa.ImportParameters(rsaParam);
string msg = ".";
byte[] encrypted = rsa.Encrypt(Encoding.UTF8.GetBytes(msg), true);
string cipherText = Convert.ToBase64String(encrypted);
File.WriteAllText(#"D:\NodeProjects\Test project\cipher-text.txt", cipherText);
Console.WriteLine(publicKey);
Console.WriteLine(cipherText);
Console.ReadLine();
}
And this is the second rsa-wrapper.js that I tried using, but also resulting in a failure:
const rsaWrapper = {};
const fs = require('fs');
const NodeRSA = require('node-rsa');
const crypto = require('crypto');
// load keys from file
rsaWrapper.initLoadServerKeys = () => {
rsaWrapper.serverPub = fs.readFileSync('./keys/public-key.pem');
rsaWrapper.serverPrivate = fs.readFileSync('./keys/private-key.pem');
};
rsaWrapper.generate = () => {
let key = new NodeRSA();
key.generateKeyPair(2048, 65537);
fs.writeFileSync('./keys/private-key.pem', key.exportKey('pkcs8-private-pem'));
fs.writeFileSync('./keys/public-key.pem', key.exportKey('pkcs8-public-pem'));
return true;
};
rsaWrapper.serverExampleEncrypt = () => {
console.log('Server public encrypting');
let enc = rsaWrapper.encrypt(rsaWrapper.serverPub, 'Server init hello');
console.log('Encrypted RSA string ', '\n', enc);
let dec = rsaWrapper.decrypt(rsaWrapper.serverPrivate, enc);
console.log('Decrypted RSA string ...');
console.log(dec);
};
rsaWrapper.encrypt = (publicKey, message) => {
let enc = crypto.publicEncrypt({
key: publicKey,
padding: crypto.RSA_PKCS1_OAEP_PADDING
}, Buffer.from(message));
return enc.toString('base64');
};
rsaWrapper.decrypt = (privateKey, message) => {
let enc = crypto.privateDecrypt({
key: privateKey,
padding: crypto.RSA_PKCS1_OAEP_PADDING
}, Buffer.from(message, 'base64'));
return enc.toString();
};
module.exports = rsaWrapper;

rsacryptoserviceprovider.VerifyData always returns false

Below is my C# Program that verifies a response from a php script which is using phpseclib
static void Main(string[] args)
{
var payment =
"VUQxMzE1MTg0OTk0MDM2MzIyMDJ8VDAwMDAxN0kxMFVEMTMxNTE4NDk5NDAzNjMyMjAyfDIwMTctMTAtMDd8MHxwYXltZW50IHN1Y2Nlc3NmdWx8MjAyNTQ=";
var signature =
"V0T9ZedZW8oB9uy4PazRIxWHvJ7rR+FVtnGjUy30mSKqgmEceZWE1aBvkQWeG4ERjAXHjsRge0D0MlHd9zvXjrLog+G5nWBHIu52O0srCd9d71JVztMQy8fV5oSnRPtlUpgdmn8QDnJ27XrbaHzNxnFyybTQhmbfxkT0oJ0MEOk=";
var sigByte = Convert.FromBase64String(signature);
var payBite = Convert.FromBase64String(payment);
Verify(payBite, sigByte);
}
public static bool Verify(byte[] payment, byte[] signature)
{
var key = Resources.PublicKey;
var cipher = Crypto.DecodeX509PublicKey(key);
var res = cipher.VerifyData(payment, "SHA256", signature);
return res;
}
the public key used is below:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSiXzUuH9ePZgSLYrzZ0qhta25
HCb+WG48wIKUl+cQNC/Fl/KZG2cSwRXdo8KZLVWWO5qwzplfTWEylg4IqRA48rYY
f/b+Y7QhORKeAws4pttLZJBbh1mIbZ9HXfQ+zBjP+zfJZ1YjSFs2uZdwSt1itUcJ
/GQFct8GoUevNELG7wIDAQAB
-----END PUBLIC KEY-----
but the verify method seems to be returning false all the time. any idea why this happens.
the same content works in the php code which the vendor gave to me
<?php
//load RSA library
include 'Crypt/RSA.php';
//initialize RSA
$rsa = new Crypt_RSA();
//decode & get POST parameters
$payment = base64_decode("VUQxMzE1MTg0OTk0MDM2MzIyMDJ8VDAwMDAxN0kxMFVEMTMxNTE4NDk5NDAzNjMyMjAyfDIwMTctMTAtMDd8MHxwYXltZW50IHN1Y2Nlc3NmdWx8MjAyNTQ=");
$signature = base64_decode("V0T9ZedZW8oB9uy4PazRIxWHvJ7rR+FVtnGjUy30mSKqgmEceZWE1aBvkQWeG4ERjAXHjsRge0D0MlHd9zvXjrLog+G5nWBHIu52O0srCd9d71JVztMQy8fV5oSnRPtlUpgdmn8QDnJ27XrbaHzNxnFyybTQhmbfxkT0oJ0MEOk=");
//load public key for signature matching
$publickey = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSiXzUuH9ePZgSLYrzZ0qhta25
HCb+WG48wIKUl+cQNC/Fl/KZG2cSwRXdo8KZLVWWO5qwzplfTWEylg4IqRA48rYY
f/b+Y7QhORKeAws4pttLZJBbh1mIbZ9HXfQ+zBjP+zfJZ1YjSFs2uZdwSt1itUcJ
/GQFct8GoUevNELG7wIDAQAB
-----END PUBLIC KEY-----";
$rsa->loadKey($publickey);
//verify signature
$signature_status = $rsa->verify($payment, $signature);
//get payment response in segments
//payment format: order_id|order_refference_number|date_time_transaction|payment_gateway_used|status_code|comment;
$responseVariables = explode('|', $payment);
//display values
echo $signature_status;
echo '<br/>';
var_dump($responseVariables);
?>
Any idea what i'm doing wrong here. i tried passing "SHA512", "MD5" all in the C# code and still returns false.
PSS is supported in-the-box with .NET 4.6+, but requires using the RSACng class (CAPI, which RSACryptoServiceProvider is based on, doesn't offer it).
public static bool Verify(byte[] payment, byte[] signature)
{
var key = Resources.PublicKey;
// Change the function this calls to return RSACng instead of RSACryptoServiceProvider.
RSA cipher = Crypto.DecodeX509PublicKey(key);
// or, failing being able to change it:
RSA tmp = new RSACng();
tmp.ImportParameters(cipher.ExportParameters(false));
cipher = tmp;
return cipher.VerifyData(
payment,
signature,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pss);
}
Well, seems like the vendor is NOT using PKCS1, he's using PSS. Verify it this way (requires Bouncy Castle!):
public static bool Verify(byte[] payment, byte[] signature)
{
var pub = #"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSiXzUuH9ePZgSLYrzZ0qhta25HCb+WG48wIKUl+cQNC/Fl/KZG2cSwRXdo8KZLVWWO5qwzplfTWEylg4IqRA48rYYf/b+Y7QhORKeAws4pttLZJBbh1mIbZ9HXfQ+zBjP+zfJZ1YjSFs2uZdwSt1itUcJ/GQFct8GoUevNELG7wIDAQAB";
byte[] raw = Convert.FromBase64String(pub);
AsymmetricKeyParameter aKey = PublicKeyFactory.CreateKey(raw);
RsaKeyParameters rKey = (RsaKeyParameters)aKey;
PssSigner pss = new PssSigner(new RsaEngine(), new Sha1Digest(), 20);
pss.Init(false, rKey);
pss.BlockUpdate(payment, 0, payment.Length);
var res = pss.VerifySignature(signature);
return res;
}

Encrypt password by using Public Key (.pem) file

Now I have a Public Key(.pem) file and password to encrypt.
-----BEGIN PUBLIC KEY-----
.....
...
...
-----END PUBLIC KEY-----
I would like to get byte[] values for encrypted password.
It doesn't get any error but return byte[] values is seem to wrong.
Below are coding current my using one, pls help me or advise me if I'm going wrong.
Really appreciate for your help!!
private static UnicodeEncoding _encoder = new UnicodeEncoding();
public byte[] getPem(string pemFile, string password)
{
byte[] encryptData;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] Exponent = { 1, 0, 1 };
RSAParameters rsaParam = rsa.ExportParameters(false);
rsaParam.Modulus = Convert.FromBase64String(File.ReadAllText(pemFile).Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", ""));
rsaParam.Exponent = Exponent;
rsa.ImportParameters(rsaParam);
var dataToEncrypt = _encoder.GetBytes(password);
encryptData = rsa.Encrypt(dataToEncrypt, false);
return encryptData;
}

RSA signing and verification with C#,BouncyCastle and imported RSA key - Working Python example and non-working C# code sample inside

I have been tearing what is left of my hair out trying to get a trivial example of RSA data signing and verification with C# and BouncyCastle working.
RSACryptoServiceProvider.VerifyHash() always returns false on an example that works for me with Python and M2Crypto.
I have verified that the hash signatures are identical between the working example and the C# example and it is there I am stuck. I feel I am missing some vital detail.
The working Python code and non working C# code follow.
The key was generated with
openssl genrsa -out testkey.pem 1024
openssl rsa -in testkey.pem -pubout > testkey.pub
Python code (working):
private = """-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCxSHbp1ID/XHEdzVzgqYR1F/79PeMbqzuKNZChvt1gFObBhKyB
pgaHDHw3UZrO8s/hBEE/Mpe2Lh90ZAFdPIXq+HyVoznXMoJYBv0uLDApvSQbJNOd
f7T5VwmpBbkfj1NAlm39Eun9uBSokEOnB24g+bczPQPGOASrQ2Ly9afOZQIDAQAB
AoGBAIEzQIZ1OnXgVwfTLMcGg+QaUtkYizUU+9Vj6D4YrZliYjHSkS4DY2p0rOpb
7Ki5yMpCoZJ/OpWo03+tilj6zNUU6X3aHrPPSv8jcsE0sDi9zYJr/Ztk3EG23sad
bM28Bb4fV/Z0/E6FZJrmuvI2dZP/57oQSHGOhtkHFO21cW5BAkEA3l/i5Rc34YXc
WHYEsOYe0kAxS4dCmhbLWaWvsghW/TomjdxzePsO70GZZqRMdzkfA1iS1OrK+pP4
4suL2rSLrQJBAMwXFnBp4Jmek0CTSxoYf6q91eFm/IRkGLnzE1fEZ76vQOBTas8T
/mpjNQHSEywo/QB62h9A8hy7XNrfZJAMJJkCQA5TYwybKFBxDTbts3Op/4ZP+F0D
Q7klisglsmHnw6Lgoic1coLyuY2UTkucfgiYN3VBuYPZ9GWcLsZ9km7ufqkCQQCz
NVa70Qyqd+cfXfcla/u2pskHCtKTQf3AUmRavhjHBMa39CemvAy7yG9EMP4q2bcH
U9jydqnidtdbTavVHQSJAkA0zJtLzHGPtQqQaI7K6kBDXYPqloGnQxHxad0HPx2e
Vj2qv1tEsqeG6HC7aL/afXOtxcfjq4oMHbGUjDv+dGfP
-----END RSA PRIVATE KEY-----"""
public = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxSHbp1ID/XHEdzVzgqYR1F/79
PeMbqzuKNZChvt1gFObBhKyBpgaHDHw3UZrO8s/hBEE/Mpe2Lh90ZAFdPIXq+HyV
oznXMoJYBv0uLDApvSQbJNOdf7T5VwmpBbkfj1NAlm39Eun9uBSokEOnB24g+bcz
PQPGOASrQ2Ly9afOZQIDAQAB
-----END PUBLIC KEY-----"""
message = "test input string"
import base64
# Use EVP api to sign message
from M2Crypto import EVP
key = EVP.load_key_string(private)
key.reset_context(md='sha1')
key.sign_init()
key.sign_update(message)
signature = key.sign_final()
encoded = base64.b64encode(signature)
print encoded
with open("python_sig2.txt","w") as f:
f.write(encoded)
# Use EVP api to verify signature
from M2Crypto import BIO, RSA, EVP
bio = BIO.MemoryBuffer(public)
rsa = RSA.load_pub_key_bio(bio)
pubkey = EVP.PKey()
pubkey.assign_rsa(rsa)
pubkey.reset_context(md="sha1")
pubkey.verify_init()
pubkey.verify_update(message)
decoded = base64.b64decode(encoded)
print pubkey.verify_final(decoded) == 1
C# code (verifyhash() returns false):
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
namespace RsaSignTest
{
class Program
{
private const string privateKey =
#"-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCxSHbp1ID/XHEdzVzgqYR1F/79PeMbqzuKNZChvt1gFObBhKyB
pgaHDHw3UZrO8s/hBEE/Mpe2Lh90ZAFdPIXq+HyVoznXMoJYBv0uLDApvSQbJNOd
f7T5VwmpBbkfj1NAlm39Eun9uBSokEOnB24g+bczPQPGOASrQ2Ly9afOZQIDAQAB
AoGBAIEzQIZ1OnXgVwfTLMcGg+QaUtkYizUU+9Vj6D4YrZliYjHSkS4DY2p0rOpb
7Ki5yMpCoZJ/OpWo03+tilj6zNUU6X3aHrPPSv8jcsE0sDi9zYJr/Ztk3EG23sad
bM28Bb4fV/Z0/E6FZJrmuvI2dZP/57oQSHGOhtkHFO21cW5BAkEA3l/i5Rc34YXc
WHYEsOYe0kAxS4dCmhbLWaWvsghW/TomjdxzePsO70GZZqRMdzkfA1iS1OrK+pP4
4suL2rSLrQJBAMwXFnBp4Jmek0CTSxoYf6q91eFm/IRkGLnzE1fEZ76vQOBTas8T
/mpjNQHSEywo/QB62h9A8hy7XNrfZJAMJJkCQA5TYwybKFBxDTbts3Op/4ZP+F0D
Q7klisglsmHnw6Lgoic1coLyuY2UTkucfgiYN3VBuYPZ9GWcLsZ9km7ufqkCQQCz
NVa70Qyqd+cfXfcla/u2pskHCtKTQf3AUmRavhjHBMa39CemvAy7yG9EMP4q2bcH
U9jydqnidtdbTavVHQSJAkA0zJtLzHGPtQqQaI7K6kBDXYPqloGnQxHxad0HPx2e
Vj2qv1tEsqeG6HC7aL/afXOtxcfjq4oMHbGUjDv+dGfP
-----END RSA PRIVATE KEY-----";
private const string publicKey =
#"-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxSHbp1ID/XHEdzVzgqYR1F/79
PeMbqzuKNZChvt1gFObBhKyBpgaHDHw3UZrO8s/hBEE/Mpe2Lh90ZAFdPIXq+HyV
oznXMoJYBv0uLDApvSQbJNOdf7T5VwmpBbkfj1NAlm39Eun9uBSokEOnB24g+bcz
PQPGOASrQ2Ly9afOZQIDAQAB
-----END PUBLIC KEY-----";
static void Main(string[] args)
{
var data = "test input string";
var sig = SignWithPrivateKey(data);
var valid = VerifyWithPublicKey(data,sig);
}
private static byte[] SignWithPrivateKey(string data)
{
RSACryptoServiceProvider rsa;
using (var keyreader = new StringReader(privateKey))
{
var pemreader = new PemReader(keyreader);
var y = (AsymmetricCipherKeyPair) pemreader.ReadObject();
var rsaPrivKey = (RsaPrivateCrtKeyParameters)y.Private;
rsa = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create();
var rsaParameters = DotNetUtilities.ToRSAParameters(rsaPrivKey);
rsa.ImportParameters(rsaParameters);
}
// compute sha1 hash of the data
var sha = new SHA1CryptoServiceProvider();
byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(data));
// actually compute the signature of the SHA1 hash of the data
var sig = rsa.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
// base64 encode the signature and write to compare to the python version
String b64signature = Convert.ToBase64String(sig);
using (var sigwriter = new StreamWriter(#"C:\scratch\csharp_sig2.txt"))
{
sigwriter.Write(b64signature);
}
return sig;
}
private static 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) RSACryptoServiceProvider.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);
}
}
}
At this point I don't know how to proceed and any help would be greatly appreciated.
Something is wrong with how you're re-constructing the private/public key. Obviously in python you're note required to do that.
I created new keys that verify (in a different format) using this code:
private static void GenerateKeys(out string forPubKey, out string forPrivKey)
{
GenerateKeys(out forPubKey, out forPrivKey, 2048, 65537, 80);
}
/// <summary>
///
/// </summary>
/// <param name="forPubKey"></param>
/// <param name="forPrivKey"></param>
/// <param name="keyStrength">1024, 2048,4096</param>
/// <param name="exponent">Typically a fermat number 3, 5, 17, 257, 65537, 4294967297, 18446744073709551617,</param>
/// <param name="certaninty">Should be 80 or higher depending on Key strength number (exponent)</param>
private static void GenerateKeys(out string forPubKey, out string forPrivKey, int keyStrength, int exponent, int certaninty)
{
// Create key
RsaKeyPairGenerator generator = new RsaKeyPairGenerator();
/*
* This value should be a Fermat number. 0x10001 (F4) is current recommended value. 3 (F1) is known to be safe also.
* 3, 5, 17, 257, 65537, 4294967297, 18446744073709551617,
*
* Practically speaking, Windows does not tolerate public exponents which do not fit in a 32-bit unsigned integer. Using e=3 or e=65537 works "everywhere".
*/
BigInteger exponentBigInt = new BigInteger(exponent.ToString());
var param = new RsaKeyGenerationParameters(
exponentBigInt, // new BigInteger("10001", 16) publicExponent
new SecureRandom(), // SecureRandom.getInstance("SHA1PRNG"),//prng
keyStrength, //strength
certaninty);//certainty
generator.Init(param);
AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();
// Save to export format
SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
byte[] ret = info.GetEncoded();
forPubKey = Convert.ToBase64String(ret);
// EncryptedPrivateKeyInfo asdf = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
// DerObjectIdentifier.Ber,,,keyPair.Private);
//// demonstration: how to serialise option 1
//TextWriter textWriter = new StringWriter();
//PemWriter pemWriter = new PemWriter(textWriter);
//pemWriter.WriteObject(keyPair);
//pemWriter.Writer.Flush();
//string ret2 = textWriter.ToString();
//// demonstration: how to serialise option 1
//TextReader tr = new StringReader(ret2);
//PemReader read = new PemReader(tr);
//AsymmetricCipherKeyPair something = (AsymmetricCipherKeyPair)read.ReadObject();
//// demonstration: how to serialise option 2 (don't know how to deserailize)
//PrivateKeyInfo pKinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
//byte[] privRet = pKinfo.GetEncoded();
//string forPrivKey2Test = Convert.ToBase64String(privRet);
PrivateKeyInfo pKinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
byte[] privRet = pKinfo.GetEncoded();
string forPrivKey2Test = Convert.ToBase64String(privRet);
forPrivKey = forPrivKey2Test;
}
and then turned them back into RSA objects like this:
// Private key
RsaPrivateCrtKeyParameters kparam = ConvertToRSAPrivateKey(privateKey);
RSAParameters p1 = DotNetUtilities.ToRSAParameters(kparam);
rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(p1);
// Public key
RsaKeyParameters kparam = ConvertToRSAPublicKey(publicKey);
RSAParameters p1 = DotNetUtilities.ToRSAParameters(kparam);
rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(p1);

Categories

Resources