how to encrypt and decrypt with only public key with rsa c# - c#
I want to encrypt and decrypt the RSA using only the public key, but I get an error on the decryption side. Error: "unknown block type"
Can you help?
BigInteger rsaPubMod = new BigInteger(Base64.Decode("ALGZqqOFBDh6qULIV0hf5g+Zg5uQqTYWhrw9fzUJwWL8dW7V6kd+9kO8yD+1/f8NVmSDAWGfmVImsPNZp/8x/tF/DycPi5vfRuzHfFcT0mSgD7VW2CfuKM0Gh2WOpgXct6IMC7UsWTkPf8VBSgHobbkr+Ex5pm09mooe2KXTtXN3"));
BigInteger rsaPubExp = new BigInteger(Base64.Decode("AQAB"));
Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = new AsymmetricCipherKeyPair(new RsaKeyParameters(false, rsaPubMod, rsaPubExp), new RsaKeyParameters(true, rsaPubMod,rsaPubExp));
RsaKeyParameters pubParameters = new RsaKeyParameters(false, rsaPubMod, rsaPubExp);
IAsymmetricBlockCipher eng = new Pkcs1Encoding(new RsaEngine());
eng.Init(true, pubParameters);
byte[] encdata = Convert.FromBase64String("test");
var encdataResult = eng.ProcessBlock(encdata, 0, encdata.Length);
string result = Convert.ToBase64String(encdataResult);
IAsymmetricBlockCipher deng = new Pkcs1Encoding(new RsaEngine());
deng.Init(false, pubParameters);
byte[] decdata = Convert.FromBase64String(result);
var dencdataResult = deng.ProcessBlock(decdata, 0, decdata.Length);
string result2 = Encoding.UTF8.GetString(dencdataResult);
RSA is an asymmetric algorithm. With a public key you can encrypt, or perform signature verification. With a private key you can decrypt, perform signature creation, or create a public key.
Related
Generate key/Encryption/Decryption for RSACryptoProvider and BouncyCastle
Key generated through RSACryptoProvider is work for BouncyCastle Encryption (using publickey) / Decryption (using privatekey) ? using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { var pu = rsa.ToXmlString(false); var pr = rsa.ToXmlString(true); } Also, how to generate key using BouncyCastle ?
Answer to first question, yes, RSA is a standard and it doesn't depends on the libraries used. Second, try this: public static void GetRsaKeyPair(out string privateXml, out string publicXml) { CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom secureRandom = new SecureRandom(randomGenerator); var keyGenerationParameters = new KeyGenerationParameters(secureRandom, 1024); var rsaKeyPairGenerator = new RsaKeyPairGenerator(); rsaKeyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair rsaKeyPair = rsaKeyPairGenerator.GenerateKeyPair(); var privateRsaParameters = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)rsaKeyPair.Private); using (RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider()) { rsaProvider.ImportParameters(privateRsaParameters); privateXml = rsaProvider.ToXmlString(true); publicXml = rsaProvider.ToXmlString(false); } }
'Error: Incorrect data or key' while decrypting ciphertext using Node-RSA library
I'm using Node-RSA library to decrypt following cyphertext. AD2FrZBeg6gqxJu3KPZtyvBhYcgb3Gk/D1hVG6/1bheD+E3sRv07a4mV/9WDiB1N1om8mHRgikNEoRlecv5UsAU= But following error occurs. Error: Error during decryption (probably incorrect key). Original error: Error: Incorrect data or key at NodeRSA.module.exports.NodeRSA.$$decryptKey And my code is following. var NodeRSA = require('node-rsa'); var key = new NodeRSA(); key.importKey({ n: new Buffer('0086fa9ba066685845fc03833a9699c8baefb53cfbf19052a7f10f1eaa30488cec1ceb752bdff2df9fad6c64b3498956e7dbab4035b4823c99a44cc57088a23783', 'hex'), e: 65537, d: new Buffer('5d2f0dd982596ef781affb1cab73a77c46985c6da2aafc252cea3f4546e80f40c0e247d7d9467750ea1321cc5aa638871b3ed96d19dcc124916b0bcb296f35e1', 'hex'), p: new Buffer('00c59419db615e56b9805cc45673a32d278917534804171edcf925ab1df203927f', 'hex'), q: new Buffer('00aee3f86b66087abc069b8b1736e38ad6af624f7ea80e70b95f4ff2bf77cd90fd', 'hex'), dmp1: new Buffer('008112f5a969fcb56f4e3a4c51a60dcdebec157ee4a7376b843487b53844e8ac85', 'hex'), dmq1: new Buffer('1a7370470e0f8a4095df40922a430fe498720e03e1f70d257c3ce34202249d21', 'hex'), coeff: new Buffer('00b399675e5e81506b729a777cc03026f0b2119853dfc5eb124610c0ab82999e45', 'hex') }, 'components'); var publicComponents = key.exportKey('components-public'); console.log(publicComponents); var encrypted = 'AD2FrZBeg6gqxJu3KPZtyvBhYcgb3Gk/D1hVG6/1bheD+E3sRv07a4mV/9WDiB1N1om8mHRgikNEoRlecv5UsAU='; console.log('encrypted: ', encrypted); var decrypted = key.decrypt(encrypted,'utf8'); console.log('decrypted: ', decrypted); I predict var encrypted string is not compatible with decrypt function. UPDATE 11.16 : I got var encrypted from c# code. c# code is following RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); string publicModulus = "0086fa9ba066685845fc03833a9699c8baefb53cfbf19052a7f10f1eaa30488cec1ceb752bdff2df9fad6c64b3498956e7dbab4035b4823c99a44cc57088a23783"; byte[] publicExponent = BitConverter.GetBytes(65537); // public key generate RSAParameters publicKey = new RSAParameters(); publicKey.Modulus = StringToByteArray(publicModulus); publicKey.Exponent = publicExponent; rsa.ImportParameters(publicKey); publicKeyText = rsa.ToXmlString(false); string test = RSAEncrypt("Hello RSA!", publicKeyText); And Encrypt function is following public string RSAEncrypt(string getValue, string pubKey) { System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(pubKey); //encode into UFT8 byte[] inbuf = (new UTF8Encoding()).GetBytes(getValue); //encrypt byte[] encbuf = rsa.Encrypt(inbuf, false); //encode into Base64 return Convert.ToBase64String(encbuf); }
Error "InvalidCipherTextException: data start wrong 64" with Bouncy Castle
I am encrypting and decrypting some Data using BouncyCastle, but when the lenght of the word is too long (i don´t know exactly the value), i got this error "InvalidCipherTextException: data start wrong 64" This is my Class of Encription: public static class Crypto { public static IAsymmetricBlockCipher CriarCipher(byte[] encodingParam) { // Creating the RSA algorithm object IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest(), encodingParam); return cipher; } public static AsymmetricCipherKeyPair CreatePair() { RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator(); rsaKeyPairGnr.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair(); return keyPair; } public static byte[] Encriptar(RsaKeyParameters publicKey, string texto, byte[] encodingParam) { // Creating the RSA algorithm object IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest(), encodingParam); var palavrabyte = Encoding.UTF8.GetBytes(texto); // Initializing the RSA object for Encryption with RSA public key. Remember, for encryption, public key is needed cipher.Init(true, publicKey); byte[] ciphered = cipher.ProcessBlock(palavrabyte, 0, palavrabyte.Length); return ciphered; } public static string Decriptar(RsaKeyParameters privateKey, string txtEncript, byte[] encodingParam) { // Creating the RSA algorithm object IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest(), encodingParam); // Initializing the RSA object for Encryption with RSA public key. Remember, for encryption, public key is needed cipher.Init(false, privateKey); byte[] txtEncriptBytes = Convert.FromBase64String(txtEncript); byte[] deciphered = cipher.ProcessBlock(txtEncriptBytes, 0, txtEncriptBytes.Length); string decipheredText = Encoding.UTF8.GetString(deciphered, 0, deciphered.Length); return decipheredText; } } This is the code for OAEPE Encoding: SHA256Managed Hash = new SHA256Managed(); byte[] ParamOEAP = Hash.ComputeHash("Example" + anotherdata); And the class SHA256Managed: public class SHA256Managed { public byte[] ComputeHash(string text) { Sha256Digest dig = new Sha256Digest(); byte[] msgBytes = Encoding.UTF8.GetBytes(text); dig.BlockUpdate(msgBytes, 0, msgBytes.Length); byte[] result = new byte[dig.GetDigestSize()]; dig.DoFinal(result, 0); return result; } } When i encrypt the word, per example, "Subtracão de Incapazes", the decryption its ok. When i encrypt the word, per example, "Estelionato por Emissão de Cheque sem Suficiente Provisão de Fundos", the decryption brokes in the Decriptar codeline: byte[] deciphered = cipher.ProcessBlock(txtEncriptBytes, 0, txtEncriptBytes.Length); What i am doing wrong ?
Changing on CreatePair the line: rsaKeyPairGnr.Init(new KeyGenerationParameters(new SecureRandom(), 2048)) From 1024 to 2048 !! Now, big phrases are decrypted.
RSA decryption - Key does not exist
I'm trying to encrypt and decrypt file with RSA. Encryption is working fine. But I get error when I'm decrypting. Error is key does not exist. Here is the error: http://i.imgur.com/ebF09cU.png public byte[] RSA_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes, RSAParameters RSAKeyInfo) { //initialze the byte arrays to the public key information. byte[] PublicKey = {214,46,220,83,160,73,40,39,201,155,19,202,3,11,191,178,56, 74,90,36,248,103,18,144,170,163,145,87,54,61,34,220,222, 207,137,149,173,14,92,120,206,222,158,28,40,24,30,16,175, 108,128,35,230,118,40,121,113,125,216,130,11,24,90,48,194, 240,105,44,76,34,57,249,228,125,80,38,9,136,29,117,207,139, 168,181,85,137,126,10,126,242,120,247,121,8,100,12,201,171, 38,226,193,180,190,117,177,87,143,242,213,11,44,180,113,93, 106,99,179,68,175,211,164,116,64,148,226,254,172,147}; //Values to store encrypted symmetric keys. byte[] EncryptedSymmetricKey; byte[] EncryptedSymmetricIV; byte[] encryptedBytes = null; // Set your salt here, change it to meet your flavor: // The salt bytes must be at least 8 bytes. byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; using (MemoryStream ms = new MemoryStream()) { using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(_stBitov)) { //Set RSAKeyInfo to the public key values. RSAKeyInfo.Modulus = PublicKey; //Import key parameters into RSA. RSA.ImportParameters(RSAKeyInfo); //Create a new instance of the RijndaelManaged class. RijndaelManaged RM = new RijndaelManaged(); var key = new Rfc2898DeriveBytes(PublicKey, saltBytes, 1000); //Encrypt the symmetric key and IV. EncryptedSymmetricKey = RSA.Encrypt(RM.Key, false); EncryptedSymmetricIV = RSA.Encrypt(RM.IV, false); encryptedBytes = RSA.Encrypt(bytesToBeEncrypted, false); } } return encryptedBytes; } RSAParameters _RSAKeyInfo; public void EncryptFile() { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); //Get an instance of RSAParameters from ExportParameters function. RSAParameters RSAKeyInfo = RSA.ExportParameters(false); _RSAKeyInfo = RSAKeyInfo; string path = ofd.FileName; if (File.Exists(path)) { string dirPath = Path.GetDirectoryName(path); byte[] bytesToBeEncrypted = File.ReadAllBytes(path); byte[] passwordBytes = File.ReadAllBytes(dirPath + "/KEY_" + ofd.SafeFileName); byte[] bytesEncrypted = RSA_Encrypt(bytesToBeEncrypted, passwordBytes, RSAKeyInfo); string fileEncrypted = dirPath + "/ENCRYPTED_" + ofd.SafeFileName; File.WriteAllBytes(fileEncrypted, bytesEncrypted); } } private void button5_Click(object sender, EventArgs e) { string path = ofd2.FileName; if (File.Exists(path)) { DecryptFile(); richTextBox4.Text = "Dekripcija uspesna"; } else { richTextBox6.Text = "Datoteka ni dodana"; } } private void richTextBox4_TextChanged(object sender, EventArgs e) { } public byte[] RSA_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes, RSAParameters RSAKeyInfo) { byte[] PublicKey = {214,46,220,83,160,73,40,39,201,155,19,202,3,11,191,178,56, 74,90,36,248,103,18,144,170,163,145,87,54,61,34,220,222, 207,137,149,173,14,92,120,206,222,158,28,40,24,30,16,175, 108,128,35,230,118,40,121,113,125,216,130,11,24,90,48,194, 240,105,44,76,34,57,249,228,125,80,38,9,136,29,117,207,139, 168,181,85,137,126,10,126,242,120,247,121,8,100,12,201,171, 38,226,193,180,190,117,177,87,143,242,213,11,44,180,113,93, 106,99,179,68,175,211,164,116,64,148,226,254,172,147}; //Values to store encrypted symmetric keys. byte[] EncryptedSymmetricKey; byte[] EncryptedSymmetricIV; byte[] decryptedBytes = null; // Set your salt here, change it to meet your flavor: // The salt bytes must be at least 8 bytes. byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; using (MemoryStream ms = new MemoryStream()) { using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(_stBitov)) { //Set RSAKeyInfo to the public key values. RSAKeyInfo.Modulus = PublicKey; //Import key parameters into RSA. RSA.ImportParameters(RSAKeyInfo); //Create a new instance of the RijndaelManaged class. RijndaelManaged RM = new RijndaelManaged(); //Encrypt the symmetric key and IV. EncryptedSymmetricKey = RSA.Encrypt(RM.Key, false); EncryptedSymmetricIV = RSA.Encrypt(RM.IV, false); decryptedBytes = RSA.Decrypt(bytesToBeDecrypted, false); } } return decryptedBytes; } public void DecryptFile() { string path = ofd2.FileName; if (File.Exists(path)) { string dirPath = Path.GetDirectoryName(path); byte[] bytesToBeDecrypted = File.ReadAllBytes(path); byte[] passwordBytes = File.ReadAllBytes(dirPath + "/KEY_" + ofd.SafeFileName); byte[] bytesDecrypted = RSA_Decrypt(bytesToBeDecrypted, passwordBytes, _RSAKeyInfo); string file = dirPath + "/DECRYPTED_" + ofd.SafeFileName; File.WriteAllBytes(file, bytesDecrypted); } } Can somebody tell me what to do that decryption is going to work.
RSA is a kind of public-key cryptography. That means you need a public key to encrypt the message and a private key to decrypt your message. It looks like you're using your public key for both encryption and decryption. Where's your private key?
It seems you're trying to do hybrid encryption with RSA+AES, but you forgot to actually use AES to encrypt the plaintext and you forgot to encrypt the symmetric key with RSA. You also need to generate the symmetric key randomly and should not be derived from the public key which is supposed to be constant and public. The error that you presented here is the least of your problems, but as ElectroByt already said, you need to use a private key (RSACryptoServiceProvider#ExportParameters(true)) to decrypt something with RSA. In your case, you would need to decrypt with RSA to get the symmetric key to use it to decrypt the symmetric ciphertext to get the actual message back.
RSA Decryption using BouncyCastle with private PEM file not working
I'm doing some tests with BouncyCastle in C# and I want to encrypt some data and decrypt it later with a pair of keys that I have in my computer stored as PEM files. public static string RSABouncyEncrypt(string content) { var bytesToEncrypt = Encoding.UTF8.GetBytes(content); AsymmetricKeyParameter keyPair; using (var reader = File.OpenText(#"C:\Users\Diego\Documents\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); System.Windows.MessageBox.Show(cryptMessage); //Decrypt before return statement to check that it has been encrypted correctly RSADecrypt(cryptMessage); return cryptMessage; } public static void RSADecrypt(string string64) { var bytesToDecrypt = Convert.FromBase64String(string64); // string to decrypt, base64 encoded AsymmetricCipherKeyPair keyPair; using (var reader = File.OpenText(#"C:\Users\Diego\Documents\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); System.Windows.MessageBox.Show(decrypted); } The RSADecrypt function shows an error. when I show the message box after decrypting I get this: ���Z��8o>>���;;�/�Z�ב?���#�F��(͌5���o1I�,���4� S�W��)��w��x�4p�$-|А���&��Rv}�G��V�c ��&wU? �D�� }E���O����7�n��!(e��E��$y�g9ςOأ��P�� �t�d�T�nN��K$�bQ��!�v���-�Hb���1���?����#B�y� r��Le�h=*Yr�w �l�W|�嘟��|g��EV��#�[��M which is definitely not what I encrypted. What am I doing wrong?
Actually the answer why it is not working is that there is no information about padding. Correct way how to instantiate RsaEngine is sth. like this var decryptEngine = new Pkcs1Encoding(RsaEngine()) var bytesToDecrypt = Convert.FromBase64String(string64); // string to decrypt, base64 encoded AsymmetricCipherKeyPair keyPair; using (var reader = File.OpenText(#"C:\Users\Diego\Documents\private.pem")) keyPair = (AsymmetricCipherKeyPair)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject(); var decryptEngine = new Pkcs1Encoding(RsaEngine()); decryptEngine.Init(false, keyPair.Private); var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length)); Logs.Log.LogMessage("decrypted: " + decrypted); System.Windows.MessageBox.Show(decrypted);
I reproduced this problem and it happened because you used a private key and a public key that don't match. In other words the message was encrypted with a private key (let's call it private_key_1) that came from one pair (private_key_1/public_key_1) but you tried to decrypt it with a public key (let's call it publick_key_2) that came from a different pair (private_key_2/public_key_2). Try to generate a new key pair and use it in your example e.g.: var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024)); var keyPair = kpgen.GenerateKeyPair(); using (var writer = new StreamWriter(File.OpenWrite(#"C:\Users\Diego\Documents\private2.pem"))) { new PemWriter(writer).WriteObject(keyPair.Private); } using (var writer = new StreamWriter(File.OpenWrite(#"C:\Users\Diego\Documents\public2.pem"))) { new PemWriter(writer).WriteObject(keyPair.Public); }