I need a RSA public key encoded into DER format.
The key-pair is generated using RSACryptoServiceProvider.
What I'm looking for is the c# equivalent to the java:
PublicKey pubKey = myPair.getPublic();
byte[] keyBytes = pubKey.getEncoded();
I have tried looking into BouncyCastle but got lost so if the solution is there any pointers are welcome.
Using Bouncy Castle:
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
...
var generator = new RsaKeyPairGenerator ();
generator.Init (new KeyGenerationParameters (new SecureRandom (), 1024));
var keyPair = generator.GenerateKeyPair ();
RsaKeyParameters keyParam = (RsaKeyParameters)keyPair.Public;
var info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo (keyParam);
RsaBytes = info.GetEncoded ();
The last three lines are the ones who take the RSA public key and export it.
I tried to use aforementioned info.GetEncoded() but as a result, I couldn't use it to verify the signature created with the corresponding private key.
What works for me is converting it to a X509Certificate2.
private bool VerifySignature(string stringContent, string stringSignature, X509Certificate2 x509PublicKey)
{
Int16 cbSignature = 0, cbCert = 0;
int cbData = 0;
CertBasicStruct sCert = new CertBasicStruct();
var pbCert = PublicKey.RawData;
cbCert = (Int16)pbCert.Length;
byte[] pbData = Encoding.UTF8.GetBytes(stringContent);
cbData = (Int16)pbData.Length;
byte[] pbSignature = Convert.FromBase64String(Signature);
cbSignature = (Int16)pbSignature.Length;
var rtn = DllImportService.DecodeCertificate(pbCert, cbCert, ref sCert);
var rtn_1 = DllImportService.VerifySignatureByCert(ref sCert, DllImportService.CKM_SHA256_RSA_PKCS, pbData, cbData, pbSignature, cbSignature);
if (rtn_1 == 0)
{
LogWndAppendLine("Signature is valid.");
return true;
}
else
{
LogWndAppendLine("Signature is invalid");
return false;
}
}
X509Certificate2.RawData would be what you are looking for.
Related
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!
I am creating a crypto class to use in both my chat client(Windows, .NET Framework) & server(Linux, .NET Core).
I figured I'd use BouncyCastle since its "Well documented", and since i need cross-platform which default lib doesn't support (CNG classes).
So i got the key generation working (Haven't tested it cross-platform yet), but the encryption and decryption is not working dues to invalid key size.
I cant find any docs on this and have been stuck here for a while.
Please point out if there's anything I'm doing horribly wrong
(I'm very new to crypto, C#... Well programming in general, been learning for 1 year)
I really hope my code isn't a total mess:
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Security;
using System;
using System.IO;
using System.Text;
namespace ChatClient
{
public class Crypto
{
private bool _ready = false;
private X9ECParameters m_x9EC;
private ECPublicKeyParameters m_myPubKey;
private AsymmetricKeyParameter m_myPrivKey;
private byte[] m_sharedSecret = null;
public Crypto()
{
// Get curve
m_x9EC = NistNamedCurves.GetByName("P-521");
ECDomainParameters ecDomain = new ECDomainParameters(m_x9EC.Curve, m_x9EC.G, m_x9EC.N, m_x9EC.H, m_x9EC.GetSeed());
// Create generator
ECKeyPairGenerator g = (ECKeyPairGenerator)GeneratorUtilities.GetKeyPairGenerator("ECDH");
g.Init(new ECKeyGenerationParameters(ecDomain, new SecureRandom()));
// Generate keypair
AsymmetricCipherKeyPair keyPair = g.GenerateKeyPair();
// Set keys
m_myPubKey = (ECPublicKeyParameters)keyPair.Public;
m_myPrivKey = keyPair.Private;
}
public void GenPrivateKey(byte[] key)
{
// Why whould anyone even...
if (key == null)
throw new ArgumentNullException();
// Split up the Base64-Encoded, comma-seperated crypto-coords of the server/client
string str = Encoding.UTF8.GetString(key);
string[] elements = str.Split(',');
if (elements.Length != 2)
throw new ArgumentException();
// Generate a key out of the coordinates
ECPoint point = m_x9EC.Curve.CreatePoint(
new BigInteger(Convert.FromBase64String(elements[0])),
new BigInteger(Convert.FromBase64String(elements[1]))
);
// Get public key
ECPublicKeyParameters remotePubKey = new ECPublicKeyParameters("ECDH", point, SecObjectIdentifiers.SecP521r1);
// Generate shared secret key
IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");
aKeyAgree.Init(m_myPrivKey);
m_sharedSecret = aKeyAgree.CalculateAgreement(remotePubKey).ToByteArray();
// Debugging...
Console.WriteLine("Key: {0}", Convert.ToBase64String(m_sharedSecret));
// Authentication is done, class can now be used for encryption/decryption
_ready = true;
}
public byte[] GetPublicKey()
{
// Assemble the Base64-Encoded, comma-seperated crypto-coords to send to the other client/server
string str = string.Format(
"{0},{1}",
Convert.ToBase64String(m_myPubKey.Q.AffineXCoord.ToBigInteger().ToByteArray()),
Convert.ToBase64String(m_myPubKey.Q.AffineYCoord.ToBigInteger().ToByteArray())
);
// Return it
return Encoding.UTF8.GetBytes(str);
}
public byte[] Encrypt(byte[] unencryptedData)
{
// Keys need to be generated before we can start encrypting/decrypring, And please dont pass null into here...
if (!_ready || unencryptedData == null)
return null;
using (MemoryStream ms = new MemoryStream())
{
using (System.Security.Cryptography.AesManaged cryptor = new System.Security.Cryptography.AesManaged())
{
// Set parameters
cryptor.Mode = System.Security.Cryptography.CipherMode.CBC;
cryptor.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
cryptor.KeySize = 128;
cryptor.BlockSize = 128;
// Get iv
byte[] iv = cryptor.IV;
// Encrypt the data
using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, cryptor.CreateEncryptor(m_sharedSecret, iv), System.Security.Cryptography.CryptoStreamMode.Write))
cs.Write(unencryptedData, 0, unencryptedData.Length);
// Get stuff that was encrpyted
byte[] encryptedContent = ms.ToArray();
// Create a new array for the data + iv
byte[] result = new byte[iv.Length + encryptedContent.Length];
//copy both arrays into one
System.Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
System.Buffer.BlockCopy(encryptedContent, 0, result, iv.Length, encryptedContent.Length);
// Aaaand return it
return result;
}
}
return null;
}
public byte[] Decrypt(byte[] encryptedData)
{
// Keys need to be generated before we can start encrypting/decrypring, And please dont pass null into here...
if (!_ready || encryptedData == null)
return null;
// New arrays for iv and data
byte[] iv = new byte[16];
byte[] dat = new byte[encryptedData.Length - iv.Length];
// Get iv and data
System.Buffer.BlockCopy(encryptedData, 0, iv, 0, iv.Length);
System.Buffer.BlockCopy(encryptedData, iv.Length, dat, 0, dat.Length);
using (MemoryStream ms = new MemoryStream())
{
using (System.Security.Cryptography.AesManaged cryptor = new System.Security.Cryptography.AesManaged())
{
// Set parameters
cryptor.Mode = System.Security.Cryptography.CipherMode.CBC;
cryptor.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
cryptor.KeySize = 128;
cryptor.BlockSize = 128;
// Decrypt the data
using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, cryptor.CreateDecryptor(m_sharedSecret, iv), System.Security.Cryptography.CryptoStreamMode.Write))
cs.Write(encryptedData, 0, encryptedData.Length);
// Aaaand return it
return ms.ToArray();
}
}
return null;
}
}
}
Where this part:
// Encrypt the data
using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, cryptor.CreateEncryptor(m_sharedSecret, iv), System.Security.Cryptography.CryptoStreamMode.Write))
Throws this error:
Exception thrown: 'System.ArgumentException' in System.Core.dll
An unhandled exception of type 'System.ArgumentException' occurred in System.Core.dll
The specified key is not a valid size for this algorithm.
Closing this question, it was answered by Topaco in the comments
In the code the shared secret is used directly as symmetric key, which causes the error due to the different sizes. Instead, the symmetric key (with the appropriate size) is usually derived from the shared secret, here and here.
I am running below code to get public and private key only, but it seems it outputs the whole XML format. I only need to output the keys as shown in Public and Private Key demo
static RSACryptoServiceProvider rsa;
private RSAParameters _privateKey;
private RSAParameters _publicKey;
public RSACrypto()
{
rsa = new RSACryptoServiceProvider(2048);
_privateKey = rsa.ExportParameters(true);
_publicKey = rsa.ExportParameters(false);
}
public string GetPublicKeyString()
{
var sw = new StringWriter();
var xs = new XmlSerializer(typeof(RSAParameters));
xs.Serialize(sw, _publicKey);
return sw.ToString();
}
public string GetPrivateKeyString()
{
var sw = new StringWriter();
var xs = new XmlSerializer(typeof(RSAParameters));
xs.Serialize(sw, _privateKey);
return sw.ToString();
}
Starting in .NET Core 3.0, this is (largely) built-in.
Writing SubjectPublicKeyInfo and RSAPrivateKey
.NET Core 3.0 built-in API
The output of the builtin API is the binary representation, to make them PEM you need to output the header, footer, and base64:
private static string MakePem(byte[] ber, string header)
{
StringBuilder builder = new StringBuilder("-----BEGIN ");
builder.Append(header);
builder.AppendLine("-----");
string base64 = Convert.ToBase64String(ber);
int offset = 0;
const int LineLength = 64;
while (offset < base64.Length)
{
int lineEnd = Math.Min(offset + LineLength, base64.Length);
builder.AppendLine(base64.Substring(offset, lineEnd - offset));
offset = lineEnd;
}
builder.Append("-----END ");
builder.Append(header);
builder.AppendLine("-----");
return builder.ToString();
}
So to produce the strings:
string publicKey = MakePem(rsa.ExportSubjectPublicKeyInfo(), "PUBLIC KEY");
string privateKey = MakePem(rsa.ExportRSAPrivateKey(), "RSA PRIVATE KEY");
Semi-manually
If you can't use .NET Core 3.0, but you can use pre-release NuGet packages, you can make use of the prototype ASN.1 writer package (which is the same code that's used internally in .NET Core 3.0; it's just that the API surface isn't finalized).
To make the public key:
private static string ToSubjectPublicKeyInfo(RSA rsa)
{
RSAParameters rsaParameters = rsa.ExportParameters(false);
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
writer.PushSequence();
writer.PushSequence();
writer.WriteObjectIdentifier("1.2.840.113549.1.1.1");
writer.WriteNull();
writer.PopSequence();
AsnWriter innerWriter = new AsnWriter(AsnEncodingRules.DER);
innerWriter.PushSequence();
WriteRSAParameter(innerWriter, rsaParameters.Modulus);
WriteRSAParameter(innerWriter, rsaParameters.Exponent);
innerWriter.PopSequence();
writer.WriteBitString(innerWriter.Encode());
writer.PopSequence();
return MakePem(writer.Encode(), "PUBLIC KEY");
}
And to make the private key:
private static string ToRSAPrivateKey(RSA rsa)
{
RSAParameters rsaParameters = rsa.ExportParameters(true);
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
writer.PushSequence();
writer.WriteInteger(0);
WriteRSAParameter(writer, rsaParameters.Modulus);
WriteRSAParameter(writer, rsaParameters.Exponent);
WriteRSAParameter(writer, rsaParameters.D);
WriteRSAParameter(writer, rsaParameters.P);
WriteRSAParameter(writer, rsaParameters.Q);
WriteRSAParameter(writer, rsaParameters.DP);
WriteRSAParameter(writer, rsaParameters.DQ);
WriteRSAParameter(writer, rsaParameters.InverseQ);
writer.PopSequence();
return MakePem(writer.Encode(), "RSA PRIVATE KEY");
}
Reading them back
.NET Core 3.0 built-in API
Except that .NET Core 3.0 doesn't understand PEM encoding, so you have to do PEM->binary yourself:
private const string RsaPrivateKey = "RSA PRIVATE KEY";
private const string SubjectPublicKeyInfo = "PUBLIC KEY";
private static byte[] PemToBer(string pem, string header)
{
// Technically these should include a newline at the end,
// and either newline-or-beginning-of-data at the beginning.
string begin = $"-----BEGIN {header}-----";
string end = $"-----END {header}-----";
int beginIdx = pem.IndexOf(begin);
int base64Start = beginIdx + begin.Length;
int endIdx = pem.IndexOf(end, base64Start);
return Convert.FromBase64String(pem.Substring(base64Start, endIdx - base64Start));
}
Once that's done you can now load the keys:
using (RSA rsa = RSA.Create())
{
rsa.ImportRSAPrivateKey(PemToBer(pemPrivateKey, RsaPrivateKey), out _);
...
}
using (RSA rsa = RSA.Create())
{
rsa.ImportSubjectPublicKeyInfo(PemToBer(pemPublicKey, SubjectPublicKeyInfo), out _);
...
}
Semi-manually
If you can't use .NET Core 3.0, but you can use pre-release NuGet packages, you can make use of the prototype ASN.1 reader package (which is the same code that's used internally in .NET Core 3.0; it's just that the API surface isn't finalized).
For the public key:
private static RSA FromSubjectPublicKeyInfo(string pem)
{
AsnReader reader = new AsnReader(PemToBer(pem, SubjectPublicKeyInfo), AsnEncodingRules.DER);
AsnReader spki = reader.ReadSequence();
reader.ThrowIfNotEmpty();
AsnReader algorithmId = spki.ReadSequence();
if (algorithmId.ReadObjectIdentifierAsString() != "1.2.840.113549.1.1.1")
{
throw new InvalidOperationException();
}
algorithmId.ReadNull();
algorithmId.ThrowIfNotEmpty();
AsnReader rsaPublicKey = spki.ReadSequence();
RSAParameters rsaParameters = new RSAParameters
{
Modulus = ReadNormalizedInteger(rsaPublicKey),
Exponent = ReadNormalizedInteger(rsaPublicKey),
};
rsaPublicKey.ThrowIfNotEmpty();
RSA rsa = RSA.Create();
rsa.ImportParameters(rsaParameters);
return rsa;
}
private static byte[] ReadNormalizedInteger(AsnReader reader)
{
ReadOnlyMemory<byte> memory = reader.ReadIntegerBytes();
ReadOnlySpan<byte> span = memory.Span;
if (span[0] == 0)
{
span = span.Slice(1);
}
return span.ToArray();
}
And because the private key values have to have the correct size arrays, the private key one is just a little trickier:
private static RSA FromRSAPrivateKey(string pem)
{
AsnReader reader = new AsnReader(PemToBer(pem, RsaPrivateKey), AsnEncodingRules.DER);
AsnReader rsaPrivateKey = reader.ReadSequence();
reader.ThrowIfNotEmpty();
if (!rsaPrivateKey.TryReadInt32(out int version) || version != 0)
{
throw new InvalidOperationException();
}
byte[] modulus = ReadNormalizedInteger(rsaPrivateKey);
int halfModulusLen = (modulus.Length + 1) / 2;
RSAParameters rsaParameters = new RSAParameters
{
Modulus = modulus,
Exponent = ReadNormalizedInteger(rsaPrivateKey),
D = ReadNormalizedInteger(rsaPrivateKey, modulus.Length),
P = ReadNormalizedInteger(rsaPrivateKey, halfModulusLen),
Q = ReadNormalizedInteger(rsaPrivateKey, halfModulusLen),
DP = ReadNormalizedInteger(rsaPrivateKey, halfModulusLen),
DQ = ReadNormalizedInteger(rsaPrivateKey, halfModulusLen),
InverseQ = ReadNormalizedInteger(rsaPrivateKey, halfModulusLen),
};
rsaPrivateKey.ThrowIfNotEmpty();
RSA rsa = RSA.Create();
rsa.ImportParameters(rsaParameters);
return rsa;
}
private static byte[] ReadNormalizedInteger(AsnReader reader, int length)
{
ReadOnlyMemory<byte> memory = reader.ReadIntegerBytes();
ReadOnlySpan<byte> span = memory.Span;
if (span[0] == 0)
{
span = span.Slice(1);
}
byte[] buf = new byte[length];
int skipSize = length - span.Length;
span.CopyTo(buf.AsSpan(skipSize));
return buf;
}
The Bouncycastle C# library has some helper classes that can make this relatively easy. It is not well documented unfortunately. Here is an example:
using System;
using System.IO;
using System.Security.Cryptography;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
namespace ExportToStandardFormats
{
class MainClass
{
public static void Main(string[] args)
{
var rsa = new RSACryptoServiceProvider(2048);
var rsaKeyPair = DotNetUtilities.GetRsaKeyPair(rsa);
var writer = new StringWriter();
var pemWriter = new PemWriter(writer);
pemWriter.WriteObject(rsaKeyPair.Public);
pemWriter.WriteObject(rsaKeyPair.Private);
Console.WriteLine(writer);
}
}
}
I wanted to extract public and private key as char array, and not as string. I found one solution which is a modification of answers provided by James and Vikram above. It could be helpful for someone looking for it.
public static void GenerateKeyPair()
{
char[] private_key= null;
char[] public_key=null;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
var rsaKeyPair = DotNetUtilities.GetRsaKeyPair(rsa);
//PrivateKey
MemoryStream memoryStream = new MemoryStream();
TextWriter streamWriter = new StreamWriter(memoryStream);
PemWriter pemWriter = new PemWriter(streamWriter);
pemWriter.WriteObject(rsaKeyPair.Private);
streamWriter.Flush();
byte[] bytearray = memoryStream.GetBuffer();
private_key = Encoding.ASCII.GetChars(bytearray);
//PublicKey
memoryStream = new MemoryStream();
streamWriter = new StreamWriter(memoryStream);
pemWriter = new PemWriter(streamWriter);
pemWriter.WriteObject(rsaKeyPair.Public);
streamWriter.Flush();
bytearray = memoryStream.GetBuffer();
public_key = Encoding.ASCII.GetChars(bytearray);
}
Adding on to the above answer, to get public and private key separately in string format, you can use the following code snippet.
public static void GenerateKeyPair()
{
try
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
var rsaKeyPair = DotNetUtilities.GetRsaKeyPair(rsa);
//Getting publickey
TextWriter textWriter = new StringWriter();
PemWriter pemWriter = new PemWriter(textWriter);
pemWriter.WriteObject(rsaKeyPair.Public);
publicKey = textWriter.ToString();
//Getting privatekey
textWriter = new StringWriter();
pemWriter = new PemWriter(textWriter);
pemWriter.WriteObject(rsaKeyPair.Private);
privateKey = textWriter.ToString();
Console.WriteLine("public key, {0}", publicKey);
Console.WriteLine("private key, {0}", privateKey);
}
catch (Exception e)
{
Console.WriteLine($"GenerateKeyPair Failed with {e}");
Console.WriteLine(e);
}
}
How to use Public and Private RSA keys provided as string for encryption and decryption. as i'm using RSACryptoServiceProvider, it requires XML format, so is there any possibility to use string as provided. Thanks.
You have to parse the initial string to get all vectors, public keys, exponents separately. Then convert this strings to byte and use this piece of code as an example:
RSAParameters parameters = new RSAParameters();
//here you have to set all provided exponents, vectors
parameters.Exponent = myExponent; //...and other properties
//then - create new RSA cryptoservise provider and import parameters
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.ImportParameters(parameters);
To convert string to byte use this expression - it's already tested:
public static byte[] String2ByteArray(string Hex, int j = -2) =>
(Hex.StartsWith("0x") ? Hex = Hex.Substring(2) : Hex).Where((x, i) => i % 2 == 0)
.Select(x => byte.Parse(Hex.Substring(j += 2, 2), NumberStyles.HexNumber)).ToArray();
public static Action<string> writeOutput = (x) => Debug.WriteLine(x);
And if you're given XML like so:
<RSAKeyValue>
<Modulus>…</Modulus>
<Exponent>…</Exponent>
<P>…</P>
<Q>…</Q>
<DP>…</DP>
<DQ>…</DQ>
<InverseQ>…</InverseQ>
<D>…</D>
</RSAKeyValue>
You can parse this XML to retrieve all the parameters. So assign them to
parameters.Modulus
parameters.Exponent
parameters.P
parameters.D
parameters.DP
parameters.DQ
parameters.InverseQ
Having used Bouncy castle dll, pasting key info into text file and using below code i've solved the problem:
public string RSABouncyEncrypt(string content)
{
var bytesToEncrypt = Encoding.UTF8.GetBytes(content);
AsymmetricKeyParameter keyPair;
using (var reader = File.OpenText(#"E:\......\public.pem"))
{
keyPair = (AsymmetricKeyParameter)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
}
var engine = new RsaEngine();
engine.Init(true, keyPair);
var encrypted = engine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length);
var cryptMessage = Convert.ToBase64String(encrypted);
//Logs.Log.LogMessage("encrypted: " + cryptMessage);
//Console.WriteLine(cryptMessage);
//Decrypt before return statement to check that it has been encrypted correctly
//RSADecrypt(cryptMessage);
return cryptMessage;
}
public string RSADecrypt(string string64)
{
var bytesToDecrypt = Convert.FromBase64String(string64); // string to decrypt, base64 encoded
AsymmetricCipherKeyPair keyPair;
using (var reader = File.OpenText(#"E:\.....\private.pem"))
keyPair = (AsymmetricCipherKeyPair)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
var decryptEngine = new RsaEngine();
decryptEngine.Init(false, keyPair.Private);
var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
//Logs.Log.LogMessage("decrypted: " + decrypted);
//Console.WriteLine(decrypted);
return decrypted;
}
How do I unwrap a key using RSA private key in Bouncy castle? I receive the already wrapped key which was wrapped using the RSA public key. I have the RSA key pair. I just cannot find the api in the C# Bouncy Castle that I can use to unwrap it.
This code in the C# source code (https://github.com/bcgit/bc-csharp) is currently commented out. The commented out lines for the RSA is exactly what I need, but when I try to use them it seems that its been removed or never implemented
Key key = cipher.unwrap(wrappedKey, "RSA", IBufferedCipher.PRIVATE_KEY);
The line above is exactly what I need. Why has it been commented out? The full function in WrapTest.cs is given below:
public ITestResult Perform()
{
try
{
// IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/PKCS5Padding");
IWrapper cipher = WrapperUtilities.GetWrapper("DES/ECB/PKCS5Padding");
IAsymmetricCipherKeyPairGenerator fact = GeneratorUtilities.GetKeyPairGenerator("RSA");
fact.Init(
new RsaKeyGenerationParameters(
BigInteger.ValueOf(0x10001),
new SecureRandom(),
512,
25));
AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();
AsymmetricKeyParameter priKey = keyPair.Private;
AsymmetricKeyParameter pubKey = keyPair.Public;
byte[] priKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey).GetDerEncoded();
CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator("DES");
// Key wrapKey = keyGen.generateKey();
byte[] wrapKeyBytes = keyGen.GenerateKey();
KeyParameter wrapKey = new DesParameters(wrapKeyBytes);
// cipher.Init(IBufferedCipher.WRAP_MODE, wrapKey);
cipher.Init(true, wrapKey);
// byte[] wrappedKey = cipher.Wrap(priKey);
byte[] wrappedKey = cipher.Wrap(priKeyBytes, 0, priKeyBytes.Length);
// cipher.Init(IBufferedCipher.UNWRAP_MODE, wrapKey);
cipher.Init(false, wrapKey);
// Key key = cipher.unwrap(wrappedKey, "RSA", IBufferedCipher.PRIVATE_KEY);
byte[] unwrapped = cipher.Unwrap(wrappedKey, 0, wrappedKey.Length);
//if (!Arrays.AreEqual(priKey.getEncoded(), key.getEncoded()))
if (!Arrays.AreEqual(priKeyBytes, unwrapped))
{
return new SimpleTestResult(false, "Unwrapped key does not match");
}
return new SimpleTestResult(true, Name + ": Okay");
}
catch (Exception e)
{
return new SimpleTestResult(false, Name + ": exception - " + e.ToString());
}
}
I'm not entirely clear on what you need, but you can use RSA keys to wrap and unwrap AES keys in Bouncycastle. Here is a Java example that creates an RSA keypair, saves the private key to a file, and then saves an AES key that has been wrapped in the public key.
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
public class Main {
private static final SecureRandom rand = new SecureRandom();
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024, rand);
KeyPair kp = kpg.generateKeyPair();
// Write out private key to file, PKCS8-encoded DER
Files.write(Paths.get("privkey.der"), kp.getPrivate().getEncoded());
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256, rand);
SecretKey aesKey = kg.generateKey();
Cipher c = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
c.init(Cipher.WRAP_MODE, kp.getPublic(), rand);
byte[] wrappedKey = c.wrap(aesKey);
// Write out wrapped key
Files.write(Paths.get("wrappedkey"), wrappedKey);
}
}
And here is a C# example that consumes the output from the Java example and unwraps the AES key.
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
namespace RSADecryptWithBouncy
{
class MainClass
{
private static KeyParameter Unwrap(byte [] key, AsymmetricKeyParameter privKeyParam) {
var wrapper = WrapperUtilities.GetWrapper("RSA/NONE/PKCS1PADDING");
wrapper.Init(false, privKeyParam);
var aesKeyBytes = wrapper.Unwrap(key, 0, key.Length);
return new KeyParameter(aesKeyBytes);
}
public static void Main(string[] args)
{
var privKeyBytes = File.ReadAllBytes("../../privkey.der");
var seq = Asn1Sequence.GetInstance(privKeyBytes);
var rsaKeyParams = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq));
var wrappedKey = File.ReadAllBytes("../../wrappedKey");
var aesKey2 = Unwrap(wrappedKey, rsaKeyParams);
}
}
}
You will have to adapt this to your needs.