Key not valid for use in specified state in RSA encryption - c#

here is my code.get error in encryption method
encryptedData = RSA.Encrypt(Data, DoOAEPPadding);
The method throws "Key not valid for use in specified state."
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
private void button1_Click(object sender, EventArgs e)
{
var rsa = new RSACryptoServiceProvider();
var rsaKeyPair = DotNetUtilities.GetRsaKeyPair(rsa);
var writer = new StringWriter();
var writer2 = new StringWriter();
var pemWriter = new PemWriter(writer);
var pemWriter2 = new PemWriter(writer2);
pemWriter.WriteObject(rsaKeyPair.Public);
pemWriter2.WriteObject(rsaKeyPair.Private);
string Pub = writer.ToString();
string Prv = writer2.ToString();
plaintext = ByteConverter.GetBytes(txtplain.Text);
encryptedtext = Encryption(plaintext, Pub, false);
}
get error here when encrypt data using by RSA encryption method.here pass DATA as a byte and RSA public key as a string.after that convert it to RSAParanetrs "RSA.ImportParameters(GetRSAParameters(RSAKey));"
then encrypt data get this error.
static public byte[] Encryption(byte[] Data, string RSAKey, bool DoOAEPPadding)
{
try
{
byte[] encryptedData;
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.ImportParameters(GetRSAParameters(RSAKey));
encryptedData = RSA.Encrypt(Data, DoOAEPPadding); // get error "Key not valid for use in specified state"
}
return encryptedData;
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
private static RSAParameters GetRSAParameters(string pPublicKey)
{
byte[] lDer;
int lBeginStart = "-----BEGIN PUBLIC KEY-----".Length;
int lEndLenght = "-----END PUBLIC KEY-------".Length;
string KeyString = pPublicKey.Substring(lBeginStart, (pPublicKey.Length - lBeginStart - lEndLenght));
lDer = Convert.FromBase64String(KeyString);
RSAParameters lRSAKeyInfo = new RSAParameters();
lRSAKeyInfo.Modulus = GetModulus(lDer);
lRSAKeyInfo.Exponent = GetExponent(lDer);
return lRSAKeyInfo;
}
private static byte[] GetModulus(byte[] pDer)
{
string lModulus = BitConverter.ToString(pDer).Replace("-", "").Substring(58, 256);
return StringHexToByteArray(lModulus);
}
private static byte[] GetExponent(byte[] pDer)
{
int lExponentLenght = pDer[pDer.Length - 3];
string lExponent = BitConverter.ToString(pDer).Replace("-", "").Substring((pDer.Length * 2) - lExponentLenght * 2, lExponentLenght * 2);
return StringHexToByteArray(lExponent);
}
public static byte[] StringHexToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}

Related

"Key does not exist" error in RSA asymmetric encryption decryption

I'm trying to implement an asymmetric cryptography approach using RSA algorithm
for that, I'm using the following class library from Microsoft System.Security.Cryptography
This Image Source
so based on public-key sharing, This is my architecture
Basically, I've three standalone applications
Encryption/Decryption Service, which is a class library.
WPF Application to encrypt plain text to ciphertext.
Console Application to decrypt cipher text to plain text.
so this is my Encryption/Decryption Service Backbone
public class EncryptDecryptService : IEncryptDecryptService
{
private static RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
private RSAParameters _privateKey;
private RSAParameters _publicKey;
public EncryptDecryptService()
{
_privateKey = csp.ExportParameters(true);
_publicKey = csp.ExportParameters(false);
}
public void WritePrivateKey(string _privatePath)
{
TextWriter _privateKeyTxt = new StreamWriter(_privatePath);
_privateKeyTxt.Write(GeneratePrivateKey());
_privateKeyTxt.Close();
}
public void WritePublicKey(string _publicPath)
{
TextWriter _publicKeyTxt = new StreamWriter(_publicPath);
_publicKeyTxt.Write(GeneratePublicKey());
_publicKeyTxt.Close();
}
public string GeneratePublicKey()
{
var sw = new StringWriter();
var xs = new XmlSerializer(typeof(RSAParameters));
xs.Serialize(sw, _publicKey);
return sw.ToString();
}
public string GeneratePrivateKey()
{
var sw = new StringWriter();
var xs = new XmlSerializer(typeof(RSAParameters));
xs.Serialize(sw, _privateKey);
return sw.ToString();
}
public string EncryptText(string plainText, string wpfPrivateKeyPath, string consolePublicKeyPath)
{
csp = new RSACryptoServiceProvider();
var consoleAppPublicKey = CovertRSAXMLtoRSAParam(consolePublicKeyPath, false);
var wpfAppPrivateKey = CovertRSAXMLtoRSAParam(wpfPrivateKeyPath, true);
csp.ImportParameters(consoleAppPublicKey);
csp.ImportParameters(wpfAppPrivateKey);
var data = Encoding.Unicode.GetBytes(plainText);// sample
var cypher = csp.Encrypt(data, false);
return Convert.ToBase64String(cypher);
}
public string DecryptText(string cypherText, string wpfPublicKeyPath, string consolePrivateKeyPath)
{
var dataBytes = Convert.FromBase64String(cypherText);
var consoleAppPrivateKey = CovertRSAXMLtoRSAParam(consolePrivateKeyPath, true);
var wpfAppPublicKey = CovertRSAXMLtoRSAParam(wpfPublicKeyPath, false);
csp.ImportParameters(consoleAppPrivateKey);
csp.ImportParameters(wpfAppPublicKey);
var plainText = csp.Decrypt(dataBytes, false);
return Encoding.Unicode.GetString(plainText);
}
public static RSAParameters CovertRSAXMLtoRSAParam(string _location, bool isExport)
{
string xmlContent = System.IO.File.ReadAllText(_location);
RSAParameters _publicKey = new RSAParameters();
CspParameters cspParam = new CspParameters();
cspParam.Flags = CspProviderFlags.UseMachineKeyStore;
RSACryptoServiceProvider key = new RSACryptoServiceProvider(cspParam);
key.FromXmlString(xmlContent);
_publicKey = key.ExportParameters(isExport);
return _publicKey;
}
}
Like this way I'm generating the ciphertext for a plain text in WPF application
private void Button_Click(object sender, RoutedEventArgs e)
{
var wpfPrivateKeyPath = "C:\\SERVICE\\keys\\wpf_private_key.txt";
var consolePublicKeyPath = "C:\\SERVICE\\keys\\console_public_key.txt";
objWebservice.WritePrivateKey(wpfPrivateKeyPath);
objWebservice.WritePublicKey(consolePublicKeyPath);
string _plainText = PlainTextValue.Text;
string _encryptedText = objWebservice.EncryptText(_plainText, wpfPrivateKeyPath, consolePublicKeyPath);
EncryptedTextValue.Text = _encryptedText;
}
Then that ciphertext I'm trying to convert back to previous plain text in the following way.
public static void Main(string[] args)
{
EncryptDecryptService decryptService = new EncryptDecryptService();
string encryptedText = "SDSFDSFSDFDSFSsdfsdf";
var wpfPublicKeyPath = "C:\\SERVICE\\keys\\wpf_public_key.txt";
var consolePrivateKeyPath = "C:\\SERVICE\\keys\\console_private_key.txt";
decryptService.WritePrivateKey(consolePrivateKeyPath);
decryptService.WritePublicKey(wpfPublicKeyPath);
var plaintText = decryptService.DecryptText(encryptedText, wpfPublicKeyPath, consolePrivateKeyPath);
Console.WriteLine(plaintText);
Console.ReadLine();
}
this is where an error occurring when it's going to decrypt as in this image.
what did I missed here, please if can guide me to make this correct :)

"Bad data .\r\n" Error for RSA signing data

This question might be duplicate but other solutions seem to be not working for me. I am working on RSA for the first time, so little confusing. I have public and private keys and want to sign the text using these. Below is my code:
public void RSA()
{
var publickey = "***";
var privatekey = "***";
using (var RSA = new RSACryptoServiceProvider())
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
RSAParameters myRSAParameters = RSA.ExportParameters(true);
myRSAParameters.Modulus = ByteConverter.GetBytes(publickey);
myRSAParameters.D = ByteConverter.GetBytes(privatekey);
myRSAParameters.Exponent = ByteConverter.GetBytes("5");
string signedmessage = SignData("ABC", myRSAParameters);
}
}
public static String SignData(string message, RSAParameters privatekey)
{
byte[] signedBytes;
using (var rsa = new RSACryptoServiceProvider())
{
var encoder = new UTF8Encoding();
byte[] originalData = encoder.GetBytes(message);
try
{
rsa.ImportParameters(privatekey);
signedBytes = rsa.SignData(originalData, CryptoConfig.MapNameToOID("SHA512"));
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
return Convert.ToBase64String(signedBytes);
}
Actually I am not sure about RSAParameters they are given correctly or not. After running this code this throws an exception as
"Bad data .\r\n"
Any help would be appreciated.

JWT decoding fails at the time of creating key

I have written the following to decode JWT token, with the help of stackoverflow of course. I think there seems to be an issue with the public key.
Because it fails only at the key creation.
class Program
{
static void Main(string[] args)
{
string token = "TOKEN STRING";
string key = "KEY STRING";
string result = ValidateJWT(token, key);
Console.WriteLine(result);
}
public static string ValidateJWT(string tokenTodecode, string publicKey)
{
string[] parts = tokenTodecode.Split('.');
string header = parts[0];
string payload = parts[1];
byte[] crypto = Base64UrlDecode(parts[2]);
string headerJson = Encoding.UTF8.GetString(Base64UrlDecode(header));
JObject headerData = JObject.Parse(headerJson);
string payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload));
JObject payloadData = JObject.Parse(payloadJson);
var keyBytes = Convert.FromBase64String(publicKey);
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
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);
SHA256 sha256 = SHA256.Create();
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(parts[0] + '.' + parts[1]));
RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
rsaDeformatter.SetHashAlgorithm("SHA256");
if (!rsaDeformatter.VerifySignature(hash, FromBase64Url(parts[2])))
{
return "";
}
return payloadData.ToString();
}
public static byte[] Base64UrlDecode(string arg)
{
var decrypted = ToBase64(arg);
return Convert.FromBase64String(decrypted);
}
public static string ToBase64(string arg)
{
if (arg == null)
{
throw new ArgumentNullException("arg");
}
var s = arg
.PadRight(arg.Length + (4 - arg.Length % 4) % 4, '=')
.Replace("_", "/")
.Replace("-", "+");
return s;
}
static byte[] FromBase64Url(string base64Url)
{
string padded = base64Url.Length % 4 == 0
? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
string base64 = padded.Replace("_", "/")
.Replace("-", "+");
return Convert.FromBase64String(base64);
}
}
And the following is the error I get. Can someone please help me to fix this ?
Is that the case that the key is wrong ?

Hybrid cryptography. Length of the data to decrypt is invalid

I am getting above mentioned error during a hybrid cryptography implementation.
as per https://en.wikipedia.org/wiki/Hybrid_cryptosystem
I am just stucked at the last step
My code is
private void button1_Click(object sender, EventArgs e)
{
try
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(2048, cspParams);
string publicKey =lblPublicKey.Text = Convert.ToBase64String(rsaProvider.ExportCspBlob(false));
string privateKey = lblPrivateKey.Text= Convert.ToBase64String(rsaProvider.ExportCspBlob(true));
string symmericKey = txtBoxSymmetricKey.Text = "Kamran12";
txtEncryptedData.Text = EncryptData(txtInputData.Text, symmericKey);
txtBoxEncryptedSymmetricKey.Text = RSA_Encrypt(symmericKey, publicKey);
txtBoxDescryptedSymmetricKey.Text = RSA_Decrypt(txtBoxEncryptedSymmetricKey.Text, privateKey);
txtDecryptedData.Text = DecryptData(txtEncryptedData.Text, txtBoxDescryptedSymmetricKey.Text); //getting error length of the data to decrypt is invalid
}
catch (Exception exc)
{
}
}
public static string RSA_Decrypt(string encryptedText, string privateKey)
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey));
var buffer = Convert.FromBase64String(encryptedText);
byte[] plainBytes = rsaProvider.Decrypt(buffer, false);
string plainText = Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length);
return plainText;
}
public static string RSA_Encrypt(string data, string publicKey)
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey));
byte[] plainBytes = Encoding.UTF8.GetBytes(data);
byte[] encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
return Convert.ToBase64String(encryptedBytes);
}
public string EncryptData(string data, string key)
{
string encryptedData = null;
byte[] buffer = Encoding.UTF8.GetBytes(data);
DESCryptoServiceProvider desCryptSrvckey = new DESCryptoServiceProvider
{
Key = new UTF8Encoding().GetBytes(key)
};
desCryptSrvckey.IV = desCryptSrvckey.Key;
using (MemoryStream stmCipherText = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(stmCipherText, desCryptSrvckey.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
encryptedData = Encoding.UTF8.GetString(stmCipherText.ToArray());
}
}
return encryptedData;
}
public string DecryptData(string data, string key)
{
byte[] encryptedMessageBytes = Encoding.UTF8.GetBytes(data);
string decryptedData = null;
DESCryptoServiceProvider desCryptSrvckey = new DESCryptoServiceProvider
{
Key = new UTF8Encoding().GetBytes(key)
};
desCryptSrvckey.IV = desCryptSrvckey.Key;
using (MemoryStream encryptedStream = new MemoryStream(encryptedMessageBytes))
{
using (
CryptoStream cs = new CryptoStream(encryptedStream, desCryptSrvckey.CreateDecryptor(),
CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
decryptedData = sr.ReadToEnd();
}
}
}
return decryptedData;
}
You declare encryptedData as a string. This is incorrect. Your encrypted data is bytes, not a character string. Attempting to convert raw bytes to UTF-8 text, as in encryptedData = Encoding.UTF8.GetString(stmCipherText.ToArray()); will not result in UTF-8 text but give you garbage and possibly lose data.
If you want the output from your encryption to be as text, then take the cyphertext bytes and use Convert.ToBase64String() to turn them into a text string.
When decrypting, convert the Base64 string back into bytes and decrypt the bytes.

C# DECRYPT a file using the RSA DER format Public key

I've seen a lot of questions, none really provide good answers, or if they try, they assume the one asking the question isn't asking what he actually IS asking. And just for the record, I am NOT asking about signing, encryption or PEM files!
In my case, I'll be receiving a small file of encrypted data. It has been encrypted using the private key of an RSA key pair.
The public key I have available is a DER file in the ASN.1 format, it is not a certificate as such, and it is not signed.
In Java, this is easy, in c# it is a nightmare from what I can tell.
X509Certificate2 claims "Object not found", when I try to parse it the byte array of the key.
The keys were generated with the following openSSL commands:
>openssl genrsa -out private_key.pem 2048
Generating RSA private key, 2048 bit long modulus
...........+++
....................................................................................................
...........................+++
e is 65537 (0x10001)
>openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
>openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der
writing RSA key
Edit: The code I'm trying:
private byte[] ReadBytesFromStream(string streamName)
{
using (Stream stream = this.GetType().Assembly.GetManifestResourceStream(streamName))
{
byte[] result = new byte[stream.Length];
stream.Read(result, 0, (int) stream.Length);
return result;
}
}
public void LoadPublicKey()
{
byte[] key = ReadBytesFromStream("my.namespace.Resources.public_key.der");
X509Certificate2 myCertificate;
try
{
myCertificate = new X509Certificate2(key);
}
catch (Exception e)
{
throw new CryptographicException(String.Format("Unable to open key file. {0}", e));
}
}
The ReadBytesFromStream method does return the correct byte stream, the public_key.der file is an embedded resource.
Just to polish this one off. The code below is still a bit messy though, but it does seem to be what I could get to work.
The reason we can't use public keys to decrypt a message in Windows is explained here:
http://www.derkeiler.com/Newsgroups/microsoft.public.dotnet.security/2004-05/0270.html
Next, you need the public key modulus and exponent in the c# code, somewhere, be it in a file or embedded is really not the matter here. I do use Base64 to wrap up the binary keys though. I gave up on generating a key that Windows would actually import. Besides, for what I need, the public key will be an embedded resource.
The last problem I had were that the modulus generated from the key weren't working on Windows (c#). This StackOverflow post did hold the key to solve that one, the modulus in Windows can not contain leading zeroes.
Android in-app billing Verification of Receipt in Dot Net(C#)
The modulus generated from Java didn't work on c#. Use the stripLeadingZeros code from that post to create a working Public key modulus:
private static byte[] stripLeadingZeros(byte[] a) {
int lastZero = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == 0) {
lastZero = i;
}
else {
break;
}
}
lastZero++;
byte[] result = new byte[a.length - lastZero];
System.arraycopy(a, lastZero, result, 0, result.length);
return result;
}
For starters, this is how I generated the key files:
$ openssl genrsa -out private_key.pem 2048
$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
$ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der
The Java Code:
package com.example.signing;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import jcifs.util.Base64;
public class SigningExample {
private static String PRIVATE_KEY_FILE = "private_key.der";
private static String PUBLIC_KEY_FILE = "public_key.der";
/**
* #param args
*/
public static void main(String[] args) {
SigningExample.sign();
}
private static void sign() {
try {
String text = new String(SigningExample.loadFromFile("message.xml"));
String message = Base64.encode(text.getBytes());
RSAPrivateKey privateKey = PrivateRSAKeyReader.getKeyFile(SigningExample.PRIVATE_KEY_FILE);
RSAPublicKey publicKey = PublicRSAKeyReader.getKeyFile(SigningExample.PUBLIC_KEY_FILE);
byte[] modulusBytes = publicKey.getModulus().toByteArray();
byte[] exponentBytes = publicKey.getPublicExponent().toByteArray();
modulusBytes = SigningExample.stripLeadingZeros(modulusBytes);
String modulusB64 = Base64.encode(modulusBytes);
String exponentB64 = Base64.encode(exponentBytes);
System.out.println("Copy these two into your c# code:");
System.out.println("DotNet Modulus : " + modulusB64);
System.out.println("DotNet Exponent: " + exponentB64);
// Testing
byte[] signature = SigningExample.sign(message.getBytes(), privateKey, "SHA1withRSA");
String signedMessage = message + "\n" + Base64.encode(signature);
SigningExample.saveToBase64File("message.signed", signedMessage.getBytes());
System.out.println("\nMessage :\n" + signedMessage);
String[] newkey = new String(SigningExample.loadFromBase64File("message.signed")).split("\\n");
System.out.println("Verified : " + SigningExample.verify(newkey[0].getBytes(), publicKey, "SHA1withRSA", Base64.decode(newkey[1])));
} catch (Exception e) {
e.printStackTrace();
}
}
private static byte[] stripLeadingZeros(byte[] a) {
int lastZero = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == 0) {
lastZero = i;
} else {
break;
}
}
lastZero++;
byte[] result = new byte[a.length - lastZero];
System.arraycopy(a, lastZero, result, 0, result.length);
return result;
}
private static byte[] sign(byte[] data, PrivateKey prvKey,
String sigAlg) throws Exception {
Signature sig = Signature.getInstance(sigAlg);
sig.initSign(prvKey);
sig.update(data, 0, data.length);
return sig.sign();
}
private static boolean verify(byte[] data, PublicKey pubKey,
String sigAlg, byte[] sigbytes) throws Exception {
Signature sig = Signature.getInstance(sigAlg);
sig.initVerify(pubKey);
sig.update(data, 0, data.length);
return sig.verify(sigbytes);
}
public static void saveToBase64File(String fileName, byte[] data) throws IOException {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
try {
String b64 = Base64.encode(data);
int lineLength = 64;
int idx = 0;
int len = b64.length();
while (len - idx >= lineLength) {
out.write(b64.substring(idx, idx + lineLength).getBytes());
out.write('\n');
idx += lineLength;
}
out.write(b64.substring(idx, len).getBytes());
} catch (Exception e) {
throw new IOException("Unexpected error", e);
} finally {
out.close();
}
}
public static byte[] loadFromBase64File(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuffer sb = new StringBuffer();
String buffer;
while ((buffer = br.readLine()) != null) {
sb.append(buffer);
}
return Base64.decode(sb.toString());
} catch (Exception e) {
throw new IOException("Unexpected error", e);
} finally {
br.close();
}
}
public static void saveToFile(String fileName, byte[] data) throws IOException {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
try {
out.write(data);
} catch (Exception e) {
throw new IOException("Unexpected error", e);
} finally {
out.close();
}
}
public static byte[] loadFromFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuffer sb = new StringBuffer();
String buffer;
while ((buffer = br.readLine()) != null) {
sb.append(buffer);
}
return sb.toString().getBytes();
} catch (Exception e) {
throw new IOException("Unexpected error", e);
} finally {
br.close();
}
}
}
class PrivateRSAKeyReader {
public static RSAPrivateKey getKeyFile(String filename) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
return PrivateRSAKeyReader.generateKey(keyBytes);
}
public static RSAPrivateKey getKey(String base64) throws Exception {
byte[] keyBytes = Base64.decode(base64);
return PrivateRSAKeyReader.generateKey(keyBytes);
}
private static RSAPrivateKey generateKey(byte[] keyBytes) throws Exception {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(spec);
}
}
class PublicRSAKeyReader {
public static RSAPublicKey getKeyFile(String filename) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
return PublicRSAKeyReader.generateKey(keyBytes);
}
public static RSAPublicKey getKey(String base64) throws Exception {
byte[] keyBytes = Base64.decode(base64);
return PublicRSAKeyReader.generateKey(keyBytes);
}
private static RSAPublicKey generateKey(byte[] keyBytes) throws Exception {
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(spec);
}
}
In c# this code fragment should do the tricks:
String signedMessage = ""; // load Base64 coded the message generated in Java here.
byte[] message = Convert.FromBase64String(signedMessage);
String messageString = Encoding.ASCII.GetString(message);
String[] lines = Regex.Split(messageString, "\n");
byte[] content = Convert.FromBase64String(lines[0]); // first line of the message were the content
byte[] signature = Convert.FromBase64String(lines[1]); // second line were the signature
RSACryptoServiceProvider rsaObj = new RSACryptoServiceProvider(2048);
//Create a new instance of the RSAParameters structure.
RSAParameters rsaPars = new RSAParameters();
rsaPars.Modulus = Convert.FromBase64String("insert your modulus revealed in the Java example here");
rsaPars.Exponent = Convert.FromBase64String("AQAB"); // Exponent. Should always be this.
// Import key parameters into RSA.
rsaObj.ImportParameters(rsaPars);
// verify the message
Console.WriteLine(rsaObj.VerifyData(Encoding.ASCII.GetBytes(lines[0]), "SHA1", signature));
The code is using :
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
I freely admit that packing the final message into another layer of Base64 is a little overkill and should be changed.

Categories