I am trying to use C# to read in a .pem file that contains only a RSA public key. I do not have access to the private key information, nor does my application require it. The file myprivatekey.pem file begins with
-----BEGIN PUBLIC KEY-----
and ends with
-----END PUBLIC KEY-----.
My current code is as follows:
Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair;
using (var reader = File.OpenText(#"c:\keys\myprivatekey.pem"))
keyPair = (Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
However the code throws an InvalidCastException with the message
Unable to cast object of type
'Org.BouncyCastle.Crypto.Parameters.DsaPublicKeyParameters' to type
'Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair'.
How can I use Bouncy Castle's PemReader to read only a public key, when no private key information is available?
The following code will read a public key from a given filename. The exception handling should be changed for any production code. This method returns an AsymetricKeyParameter:
public Org.BouncyCastle.Crypto.AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
{
var fileStream = System.IO.File.OpenText(pemFilename);
var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
var KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();
return KeyParameter;
}
Here's a possible solution that reads both public and private PEM files into RSACryptoServiceProvider:
public class PemReaderB
{
public static RSACryptoServiceProvider GetRSAProviderFromPem(String pemstr)
{
CspParameters cspParameters = new CspParameters();
cspParameters.KeyContainerName = "MyKeyContainer";
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParameters);
Func<RSACryptoServiceProvider, RsaKeyParameters, RSACryptoServiceProvider> MakePublicRCSP = (RSACryptoServiceProvider rcsp, RsaKeyParameters rkp) =>
{
RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rkp);
rcsp.ImportParameters(rsaParameters);
return rsaKey;
};
Func<RSACryptoServiceProvider, RsaPrivateCrtKeyParameters, RSACryptoServiceProvider> MakePrivateRCSP = (RSACryptoServiceProvider rcsp, RsaPrivateCrtKeyParameters rkp) =>
{
RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rkp);
rcsp.ImportParameters(rsaParameters);
return rsaKey;
};
PemReader reader = new PemReader(new StringReader(pemstr));
object kp = reader.ReadObject();
// If object has Private/Public property, we have a Private PEM
return (kp.GetType().GetProperty("Private") != null) ? MakePrivateRCSP(rsaKey, (RsaPrivateCrtKeyParameters)(((AsymmetricCipherKeyPair)kp).Private)) : MakePublicRCSP(rsaKey, (RsaKeyParameters)kp);
}
public static RSACryptoServiceProvider GetRSAProviderFromPemFile(String pemfile)
{
return GetRSAProviderFromPem(File.ReadAllText(pemfile).Trim());
}
}
Hope this helps someone.
In answer to c0d3Junk13, I had the same issue for a PEM private key and it took me all afternoon to find the solution using the C# BouncyCastle Version 1.7 and Visual Studio 2013 Desktop Express. Don't forget to add the project reference to BouncyCastle.Crypto.dll
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.OpenSsl;
/*
For an Active Directory generated pem, strip out everything in pem file before line:
"-----BEGIN PRIVATE KEY-----" and re-save.
*/
string privateKeyFileName = #"C:\CertificateTest\CS\bccrypto-net-1.7-bin\private_key3.pem";
TextReader reader = File.OpenText(privateKeyFileName);
Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters key;
using (reader = File.OpenText(privateKeyFileName))
{
key = (Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)new PemReader(reader).ReadObject();
}
cipher.Init(false, key);
//Decrypting the input bytes
byte[] decipheredBytes = cipher.ProcessBlock(cipheredBytes, 0, cipheredBytes.Length);
MessageBox.Show(Encoding.UTF8.GetString(decipheredBytes));
EDIT:
It looks like this depends on what type of key file you are using. For ssh-keygen keys, the private key appears to have a type of AsymmetricCipherKeyPair, but for openssl keys, the private key has a type of RsaPrivateCrtKeyParameters.
Bryan Jyh Herng Chong's answer no longer appears to work for me (at least with Bouncy Castle version v1.8.5). It appears kp.GetType().GetProperty("Private") is no longer set differently for public vs private key PEM objects. It also appears that the object returned using PemReader.ReadObject() is now directly a RsaPrivateCrtKeyParameters object, so there's no longer a need to cast through a AsymmetricCipherKeyPair object first.
I changed that line to this and it worked like a charm:
return (kp.GetType() == typeof(RsaPrivateCrtKeyParameters)) ? MakePrivateRCSP(rsaKey, (RsaPrivateCrtKeyParameters)kp)) : MakePublicRCSP(rsaKey, (RsaKeyParameters)kp);
Instead of:
keyPair = (Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
Use:
keyPair = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
Since you are only using a public key and you don't actually have a pair of keys (public & private) you can't cast it as 'AsymmetricCipherKeyPair' you should cast it as 'AsymmetricKeyParameter'.
Try the following code:
Using Org.BouncyCastle.Crypto;
string path = HttpContext.Current.Server.MapPath(#"~\key\ABCD.pem");
AsymmetricCipherKeyPair Key;
TextReader tr = new StreamReader(#path);
PemReader pr = new PemReader(tr);
Key = (AsymmetricCipherKeyPair)pr.ReadObject();
pr.Reader.Close();
tr.Close();
AsymmetricKeyParameter keaa = Key.Public;
Related
So, in my C# app I have the following code to encrypt the data:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Serialization;
namespace TEST
{
public class RSAEncrypter
{
private static RSACryptoServiceProvider RSA;
private RSAParameters _privateKey;
private RSAParameters _publicKey;
public RSAEncrypter()
{
RSA = new RSACryptoServiceProvider(2048);
_privateKey = RSA.ExportParameters(true);
_publicKey = RSA.ExportParameters(false);
}
public string Encrypt(string plainText, string publicKey)
{
RSA.FromXmlString(publicKey);
_publicKey = RSA.ExportParameters(false);
RSA.ImportParameters(_publicKey);
var data = Encoding.Unicode.GetBytes(plainText);
var cypher = RSA.Encrypt(data, false);
return Convert.ToBase64String(cypher);
}
// Gets the privatekey as a string
public string PrivateKeyString()
{
var sw = new StringWriter();
var xs = new XmlSerializer(typeof(RSAParameters));
xs.Serialize(sw, _privateKey);
return sw.ToString();
}
}
}
Which gives me, for example, a key in the following format (as a string):
<?xml version="1.0" encoding="utf-16"?>
<RSAParameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Exponent>AQAB</Exponent>
<Modulus>38Z4+7H1ADzMPO8z5+QdxXS21YBEaq9Xacf7dHFXUpK72SUAIYnfijc5RDSgGFismTNlrrOa7m/6+iIWS/yB7+esvIjgfSFm+QU2aeC16NisMuw+KvPeEr8CVMjh8F5YW1ST4qKXHXG6qIe/FM2LPVGV92O9WO1ATIDcATO8UU2rJgrxKMdmE9fawqmy/j7fwI1+FL6LCNgdvgZ3OOLLwHVcyOyj7ibiIUQAcw10qW0I4MBnQL5V8udKrhKXKoVE6rsfLZoBC9rBD62ckB7CJfMsGcAVffBvnd7SRJiTFEEPVZFqzyGk0BOeqbJkHbzKNytNkUjnFQlDX9tSLCtufQ==</Modulus>
<P>+jlZUY/lv0bMWbcWVXZ+moDF96ZQ+uKHMbpAMN18ByRmZSLZ9CeHTNEkoudOzB6R9wN8xyEmnCrDZujSB65uBILdJvsJk8TYBThp5RBbBZ1YQb30CcxhsMX2s6Gwze8CoXmBU5as6tMDh+tBpxxeYxE/crS3rP7kAM2Lr88cILM=</P>
<Q>5PDUdn/RB8dhxkjSFZS0MtrefVgYmoDNjN9O+Ru7ZzNz7eqig1zLlKytDQzmpaIv6Zvrn5Y5TBaFDp1BTVLAStu8e/RU4i7qWVu6Xm83xtgB4NDULXStyYqpeZhyilD4BsfIYeRyZ3A9wUyACQ6CU3GxuIczWYkfT3HmSy5ebA8=</Q>
<DP>nEH/8x0nXeF6b3QUMF6FBTrxZYuo+mNIBdfHijxl3ZfvkazH6t5cca4RcOF9pZ5ZjKXS4A9lqxRRXgx6TG2zKoIGVPdjrbG5LNlj17X1AXaWzMcwhIXrY5bcTqTkYlWlkOztxCNN7H7Fr7VMFG10y+zTcHBGW3P5Mj8pwipV6F0=</DP>
<DQ>DMkWVHfW6KRN5ZDzipj/Z0ep3T4qQZan5BIkiuztjlnlQ4gzAzsPc4IhN/VcfCuOmXFHu2XcVU98ptBJcVQJwSR8Zj/C7c7I76ybv+JeLxCpKjD/aHp3qiXASTYmT2suLtLBchYb/YLbMAxhqh/RT2+uCSwjxgBOa1VlExXH2Ck=</DQ>
<InverseQ>zlFNPMXsmgjWz0rA5y3stzoKDiw0mbb1rU6iSXKKOZz5djokAX1tjtcwUbzdv3I5x8m+3K1qprXURUYbZXf+ubwkoYiG4WaJDWhZ+y33Q8iK87BUKy6Q062F4XryBVagCJHKMNStiiMmFB9IdbDu/wbYh52BjrwhwncLOEYaSaQ=</InverseQ>
<D>YQvsEAv/WtkDIjIC6sBtgOK7ICB+i137pO6LyNYWrsLgIK4BPopSndiRR1kjTSu3vsEhigBuYpXB3JTH4rBhka+BpEogQWQpCjoOfSBtA8xj8bmuxGX6m1qnIin0gpAH9aPaduFYc/aMouYsIlN53V/yj9V7moNZ7VO9FfBf7UnX7yTc2/fvXz9atXepQmir2YOO41Z5KgytSF1M7R3eZq1GLTnaqRK+LCQ5cKkxqcIAtUX7BZgkLnHZs3zqLo998gXbogmkqxB4NWc9bwWjybC1CMWyZeiRuaw/Wye4GbNmpM7sfsB7GINndwCSqfJzwSetGCSca8x2wkms+5zOaQ==</D>
</RSAParameters>
So how could I decrypt a message in PHP using this key?
I found this in PHP: openssl_private_decrypt but it doesn't accept the key in this format apparently.
Ok, I found out!
So, first you need to convert the key from XML to PEM format. I found this GITHUB code which is very usefull doing that: Exports RSA key pair to PEM format.
Next, after you encrypted the data utilizing my original code in the Question, you need use php's method base64_decode before utilizing the method openssl_private_decrypt. So, in the end you'll have something like this:
<?php
$encryptedData = '
b9+nktWSdlYQWiuswcT49JJdt1mmZj87Gwwydkpiu2Xbf3n1Nc+xE5whSzgfTIIthQEVssCUk/UfNsyN2iC37nkxcQe4Xu6KsiWFYvCRZmxww24p/qi43isd1ijCS6wajrJbrpq2tvLzBZ7KhrYkEt3qPbanRRslJauzaCW8MT42HotFl7mVKJjj5p+U6p5dklkm0Uxn36a9eB8+Nt8kSum1YcUbkrS0TRhmorQxifNY99yEju3KeISq5+946tKpW+Efau0CvUF/V5mKn203T5MdO8x5z7VFejHW6dB6oDxTh9EeEyEAPPRBz734wtZxCOVODd39Ttnk6FfnnWat8w==
';
$private_key = '
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAwGbWRx8kEz5+BHt5f8/R4ka7AOBGbP1YjfhY33eUQzsh6Ygl
jAvPYXmopaSEOLWAjq/TTCGXGmSfZi0DRPGeSnNXzU6nUu1qQBC5sQYIPSph/lEV
S7jv8isVO9/vH+TGCwE0CeGiQt1QP/m72Vaux3U6nt6ddVat3rpHy4FVuuDHKF58
9HQakf5cMCz4wei4y71U/tLIj1F7P5TRqSdKMB4ZLYLDbX+32OEPMEP6DJEysAiC
oRdpBR/KCOlH3QHEF0RDuTbdgL6f8oAuN2Wvr+p+f1lnkld08+gyKma9cEBpeIB7
cjBeNNcImyhXfp8VBjjZNd//ikt7jnDle30MWQIDAQABAoIBADuxbDfCrKGf2N8x
I+AIrTiD807xRkhYTdo2O/SRGBnHxdy7ldKec2fto+pIYZFqlokueeL75PKWV3IO
8x23zQGSSaJ0DavH5xgbWFFY6sN3W9HYfD/zD9bVkQ/ziTAe/Wa6p9eM/pe6LES9
CZADudQ+RcK2lKmsC+O3bcDwzpVczzuZ1s29F6Jc2L0Q7e1ce9FfBmhl/faei7ro
5DWV30+AqhdwPppMhOWFS/walro8Sq90Kz0chaU6N1vVBEdo4dSLKYapyxJwAHhm
HfNkA+wMrsMXGd9eKpi4u8AupnJYypFdBaEEgrKIbg21LLRTyx1fFKXWdE0puG7H
0GVfoNUCgYEAxoaCzv7LslAOa8bZwGVxcvnE0tIafPwXyOldH/jqeXf53I1gOmFM
dI143wawKQES8CvrbedzP/5tNVZhdrOOekTRM61yw3xSUYY5e8Ngt/gn4KyQ0nA5
X75QjtC6VxNM6ssFpyUxQT95lvTo13avrVjhnGt3raNxwTgiqJjvTfsCgYEA+Bp5
FElve0NnfvkpYeffuF6E3mTRS44IH7qRTFrpXh31zwMxE6K3cltbRtHtuf5/7DmR
XpbeogxG4Bzzw/Y7DodV3V82ApIzyhFkN5PPfg5mR/W8cia82Q3QsRMpjYTo9TBZ
aiAsTbUz8E6KaFrS64V6KbRl84EE8XBaG7tvYrsCgYBZ4TZBzvub7EDLLMkTIRpe
6pPgurzBT0TZckX2HrTRb68Q2nTxmXGK5y4NEzMYLWNMlyXMqVf1ZhQ9bLFNk3dz
BcsNMX7e4F9Ih5No5Aja4Z/0SUx76dEf9sL0Fa33lEZjmq0hgmYtWzaKULFGM3bP
7YifT8xsMa5jwy111V+qlwKBgQCjtHwN+cKYd8pTir5WfrQsqBlN0QIUs3wCy4zR
7+6qDmTCGl4IkcYvq74Xha8xmY745KdZ3Xy7OhSODix+MfuXw47RieBOY//OJhmV
Xm97wq6Ubr3QKGVVZvs7y+QQIBHCrwtgriftglHqDzjeUId5plIMMJ9Qw+HqGXMr
d0qwvwKBgQCjNuhKMHGqG6DuYiLQjJVHA6aG87K5tfNNC8yQPOIbkIJTlSzGQIkm
66wA2PSCI+yRixm+gZWGdVcYuVvcfTHLsledLocTWBRf/2VAGlqZg1ewybGrrixF
05KXg9DcAK9HFyZryFZAXtLyAoRaS1ElcSVBtLggQreGsr8fIM5Fvw==
-----END RSA PRIVATE KEY-----
';
openssl_private_decrypt(base64_decode($encryptedData), $decriptedData, $private_key);
echo var_dump($decriptedData);
I have some code in PHP:
function get_RSAencrypt($public_key) {
global $config;
$rsa = new phpseclib\Crypt\RSA();
$rsa->setEncryptionMode(phpseclib\Crypt\RSA::ENCRYPTION_PKCS1);
$rsa->loadKey($public_key);
$requestkey = base64_encode($rsa->encrypt($config['momo_key']));
return $requestkey;
}
My public key(for eg.)
-----BEGIN RSA PUBLIC KEY-----
MEgCQQDjtTNZJnbMWXON/mhhLzENzQW8TOH/gaOZ72u6FEzfjyWSfGsP6/rMIVjY
2w44ZyqNG2p45PGmp3Y8bquPAQGnAgMBAAE=
-----END RSA PUBLIC KEY-----
PHP code work
Then I tried to find some example for C# .NET Framework 4.6, but not work.
Can someoone provide me a link?
Try this:
using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
class Test
{
static void Main()
{
var key = #"-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBAKj34GkxFhD90vcNLYLInFEX6Ppy1tPf9Cnzj4p4WGeKLs1Pt8Qu
KUpRKfFLfRYC9AIKjbJTWit+CqvjWYzvQwECAwEAAQJAIJLixBy2qpFoS4DSmoEm
o3qGy0t6z09AIJtH+5OeRV1be+N4cDYJKffGzDa88vQENZiRm0GRq6a+HPGQMd2k
TQIhAKMSvzIBnni7ot/OSie2TmJLY4SwTQAevXysE2RbFDYdAiEBCUEaRQnMnbp7
9mxDXDf6AU0cN/RPBjb9qSHDcWZHGzUCIG2Es59z8ugGrDY+pxLQnwfotadxd+Uy
v/Ow5T0q5gIJAiEAyS4RaI9YG8EWx/2w0T67ZUVAw8eOMB6BIUg0Xcu+3okCIBOs
/5OiPgoTdSy7bcF9IGpSE8ZgGKzgYQVZeN97YE00
-----END RSA PRIVATE KEY-----";
var ciphertext = "L812/9Y8TSpwErlLR6Bz4J3uR/T5YaqtTtB5jxtD1qazGPI5t15V9drWi58colGOZFeCnGKpCrtQWKk4HWRocQ==";
var ciphertextBytes = Convert.FromBase64String(ciphertext);
var rsa = RSA.Create();
var rx = new Regex("-+[^-]+-+");
key = rx.Replace(key, "")
.Replace("\r", "")
.Replace("\n", "");
var keyBytes = Convert.FromBase64String(key);
rsa.ImportRSAPrivateKey(keyBytes, out _);
var plaintextBytes = rsa.Decrypt(ciphertextBytes, RSAEncryptionPadding.Pkcs1);
var plaintext = Encoding.Default.GetString(plaintextBytes);
Console.WriteLine(plaintext);
}
}
ImportRSAPrivateKey wasn't introduced until .NET Core 3.0+ but since you're using C# .NET Framework 4.6 I think you're probably good!
As a part of my project I have to encrypt some text with RSA and I have got a public key from another company. The public key looks like this:
var publicKey="MIGfMA0GCSq2GSIb3DQEBAQUAA4GNADCBiQKBgQCgFGVfrY4jQSoZQWWygZ83roKXWD4YeT2x2p41dGkPixe73rT2IW04glatgN2vgoZsoHuOPqah5and6kAmK2ujmCHu6D1auJhE2tXP+yLkpSiYMQucDKmCsWXlC5K7OSL77TXXcfvTvyZcjObEz6LIBRzs6+FqpFbUO9SJEfh6wIDAQAB"
The problem is that I don't know what is its format and how to deserialize it to RSAParameters. Other examples on the Internet have used XML serialization. The key is created by Java.
Then I also want to know how to deserialize its related private key which I don't have access to any sample of it right now.
Update :
Here is part of my code :
var pk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiiTx4F35eWP10AFMAo8MLhCKq2ryKFG9PKKWeMLQuwMSdiQq347BkMYA+Q+YscScf7weUSTk9BHVNNfTchDwzjQrIoz6TZGggqD+ufin1Ccy0Sp6QeBMnIB89JsdzQGpVcsoTxk53grW0nYY8D+rlFvBwFicKe/tmVPVMYsEyFwIDAQAB";
...
public static RSACryptoServiceProvider ImportPublicKey(string pem)
{
//var newPem = "-----BEGIN PUBLIC KEY-----\n" + pem + "-----END PUBLIC KEY-----";
Org.BouncyCastle.OpenSsl.PemReader pr = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(Pem));
Org.BouncyCastle.Crypto.AsymmetricKeyParameter publicKey = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pr.ReadObject();
RSAParameters rsaParams = Org.BouncyCastle.Security.DotNetUtilities.ToRSAParameters((Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)publicKey);
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();// cspParams);
csp.ImportParameters(rsaParams);
return csp;
}
The posted key is a PEM encoded public key in X.509 (SPKI) format, but without header (-----BEGIN PUBLIC KEY-----) and footer (-----END PUBLIC KEY-----). This can be easily verified with an ASN.1 parser, e.g. here.
The import of such a key depends on the .NET version. .NET Core offers from v3.0 on methods that directly support the import of PKCS#1, PKCS#8 and X.509 keys, e.g. RSA.ImportSubjectPublicKeyInfo for the latter. This option is not available for .NET Framework, but BouncyCastle offers a similarly comfortable solution.
Here (see ImportPublicKey method) is an example that imports a PEM encoded public key in X.509 (SPKI) format using BouncyCastle. However, the PemReader used there expects the complete PEM data, including header and footer, both separated from the body by line breaks. Therefore, when using the public keys posted here, header and footer must be added accordingly, e.g:
using System.IO;
using System.Security.Cryptography;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
...
// from: https://gist.github.com/valep27/4a720c25b35fff83fbf872516f847863
public static RSACryptoServiceProvider ImportPublicKey(string pemBody)
{
var pem = "-----BEGIN PUBLIC KEY-----\n" + pemBody + "\n-----END PUBLIC KEY-----"; // Add header and footer
PemReader pr = new PemReader(new StringReader(pem));
AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter)pr.ReadObject();
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaKeyParameters)publicKey);
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();// cspParams);
csp.ImportParameters(rsaParams);
return csp;
}
This might be a possible duplicate but I am unable to fix it.
Below is my code in C# for tripleDES:
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
class MainClass {
public static void Main (string[] args) {
String encrypt="5241110000602040";
SymmetricAlgorithm sa= SymmetricAlgorithm.Create("TripleDES");
sa.Key= Convert.FromBase64String("FRSF1P3b6fHiW/DXrK8ZJks5KAiyNpP0");
sa.IV=Convert.FromBase64String("YFKA0QlomKY=");
byte[] iba=Encoding.ASCII.GetBytes(encrypt);
MemoryStream mS=new MemoryStream();
ICryptoTransform trans=sa.CreateEncryptor();
byte[] buf= new byte[2049];
CryptoStream cs=new CryptoStream(mS,trans,CryptoStreamMode.Write);
cs.Write(iba,0,iba.Length);
cs.FlushFinalBlock();
Console.WriteLine(Convert.ToBase64String(mS.ToArray()));
}
}
Encrypted value is
Nj7GeyrbJB93HZLplFZwq5HRjxnvZSvU
I want to achieve the same thing with crypto-js library of nodejs. Here is nodejs code of what I tried:
var CryptoJS = require("crypto-js");
var text = "5241110000602040";
var key = "FRSF1P3b6fHiW/DXrK8ZJks5KAiyNpP0";
var options = {
// mode: CryptoJS.mode.ECB,
// padding: CryptoJS.pad.Pkcs7,
iv: CryptoJS.enc.Hex.parse("YFKA0QlomKY=")
};
var textWordArray = CryptoJS.enc.Utf8.parse(text);
var keyHex = CryptoJS.enc.Hex.parse(key);
var encrypted = CryptoJS.TripleDES.encrypt(textWordArray, keyHex, options);
var base64String = encrypted.toString();
console.log('encrypted val: ' + base64String);
Expected output
Nj7GeyrbJB93HZLplFZwq5HRjxnvZSvU
Actual Output
NXSBe9YEiGs5p6VHkzezfdcb5o08bALB
Encrypted value in nodejs is different than C#. What am I doing wrong?
You differently decode key and iv.
In c# you use base64:
sa.Key= Convert.FromBase64String("FRSF1P3b6fHiW/DXrK8ZJks5KAiyNpP0");
sa.IV=Convert.FromBase64String("YFKA0QlomKY=");
in node.js hex:
iv: CryptoJS.enc.Hex.parse("YFKA0QlomKY=")
var key = "FRSF1P3b6fHiW/DXrK8ZJks5KAiyNpP0";
var keyHex = CryptoJS.enc.Hex.parse(key);
Try to use base64 in both cases.
I'm busy trying to port Java code that looks like this
Cipher rsa = Cipher.getInstance("RSA/ECB/nopadding");
rsa.init(Cipher.DECRYPT_MODE, RSAPrivateKey);
decryptedData = rsa.doFinal(data, 0, 128);
to C#, but as it seems the RSACryptoServiceProvider, forces you to either use OEAP or PKCS1 padding. I know no padding isn't secure, but in this case Im working with a closed source client, so I can't do anything about that. Is there any way around this padding issue?
You might want to get the code from BouncyCastle, http://www.bouncycastle.org/csharp/, and modify the code from the link below, and ensure that it can use the encryption that you list above.
http://www.java2s.com/Code/Java/Security/Whatisinbouncycastlebouncycastle.htm
BouncyCastle will help us to make nopadding RSA encryption.
public string RsaEncryptWithPublic(string clearText, string publicKey)
{
// analogue of Java:
// Cipher rsa = Cipher.getInstance("RSA/ECB/nopadding");
try
{
var bytesToEncrypt = Encoding.ASCII.GetBytes(clearText);
var encryptEngine = new RsaEngine(); // new Pkcs1Encoding (new RsaEngine());
using (var txtreader = new StringReader("-----BEGIN PUBLIC KEY-----\n" + publicKey+ "\n-----END PUBLIC KEY-----"))
{
var keyParameter = (AsymmetricKeyParameter)new PemReader(txtreader).ReadObject();
encryptEngine.Init(true, keyParameter);
}
var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));
return encrypted;
}
catch
{
return "";
}
}
also dont forget to put it at top:
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.OpenSsl;