Symmetric encryption in BouncyCastle - c#

KeyParameter param = new KeyParameter(password);
cipher.Init(true, param);
PaddedBufferedBlockCipher blockCipher = new PaddedBufferedBlockCipher(cipher, new ZeroBytePadding());
This is how I set up my cipher in BouncyCastle. How come there is no IV to choose or block mode? How does it work?

So there are a few things to know about Bouncy Castle. Compared to the Java JCE or .NET classes there are multiple layers to each full cipher:
the block cipher;
the mode;
the buffering and padding.
Furthermore, there is a base CipherParameters class that contains instances that are accepted by all these classes. It is type-checked within the different cipher classes and if information is required then it is extracted, otherwise it is generally just handed to the parent.
OK, so that may all be a bit abstract, so I've created an example where first a block cipher instance is created, then that is used to generate a mode of operation and finally a buffered instance that also performs the padding.
I've deliberately used the interface type for the variables so you can see the inheritance structure.
Oh yeah, and I've used Java, but the general structure is of course the same across the Java and C# API.
package se.so;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.paddings.ZeroBytePadding;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
public class PaddedBufferedBC {
private static final boolean FOR_ENCRYPTION = true;
public static void main(String[] args) {
byte[] keyData = new byte[16];
CipherParameters key = new KeyParameter(keyData);
byte[] ivData = new byte[16];
CipherParameters keyAndIV = new ParametersWithIV(key, ivData);
// absorbs the key
BlockCipher blockCipher = new AESEngine();
// absorbs the IV (missing in the code of the question)
BlockCipher cbcBlockCipher = new CBCBlockCipher(blockCipher);
// simply passes on the key and IV
PaddedBufferedBlockCipher bufferedBlockCipher =
new PaddedBufferedBlockCipher(cbcBlockCipher, new ZeroBytePadding());
// initialization should be on the last wrapper class
bufferedBlockCipher.init(FOR_ENCRYPTION, keyAndIV);
// just to test that I didn't make any mistakes
System.out.println(bufferedBlockCipher.getUpdateOutputSize(100));
}
}
Note that stream ciphers or ciphers in streaming mode (e.g. counter mode, SICBlockCipher) may not need to be wrapped with a PaddedBufferedBlockCipher.

Related

How to properly verify data with rsa?

I want to sign a message with a private key and verify it with a public key, but I can't get it to work..
Here is how I sign the data (edited, but still not working):
public static string SignData(string message, string privateKey) {
byte[] plainText = ASCIIEncoding.Unicode.GetBytes(message);
var rsaWrite = new RSACryptoServiceProvider();
rsaWrite.FromXmlString(privateKey);
byte[] signature = rsaWrite.SignData(plainText, new SHA1CryptoServiceProvider());
return Convert.ToBase64String(signature);
}
Here is how I test the data (edited, still not working):
public static bool VerifyData(string sign, string publicKey, string orig) {
byte[] signature = Convert.FromBase64String(sign);
byte[] original = ASCIIEncoding.Unicode.GetBytes(orig);
var rsaRead = new RSACryptoServiceProvider();
rsaRead.FromXmlString(publicKey);
if (rsaRead.VerifyData(original, new SHA1CryptoServiceProvider(), signature)) {
return true;
} else {
return false;
}
}
I store the keypair as an xml string inside my account class. This function is executed in the constructor of account.cs:
public void addKeys() {
RSACryptoServiceProvider provider = new RSACryptoServiceProvider(1024);
privateKey = provider.ToXmlString(true);
publicKey = provider.ToXmlString(false);
}
I test the overall thing with this:
string signedHash = Utility.SignData("test" ,account.privateKey);
if (Utility.VerifyData(signedHash, account.publicKey, "test")) {
Console.WriteLine("WORKING!");
} else {
Console.WriteLine("SIGNING NOT WORKING");
}
Why isn't the overall thing working? My guess is that it doesn't work because of some encoding stuff.
return ASCIIEncoding.Unicode.GetString(signature);
The signature is arbitrary binary data, it isn't necessarily legal Unicode/UCS-2. You need to use an arbitrary encoding (https://en.wikipedia.org/wiki/Binary-to-text_encoding#Encoding_standards) to encode all of the arbitrary data. The most popular transport for signatures is Base64, so you'd want
return Convert.ToBase64String(signature);
And, of course, use Convert.FromBase64String in the verify method.
If you're compiling with a target of .NET 4.6 or higher you can also make use of the newer sign/verify API:
rsaRead.VerifyData(original, new SHA1CryptoServiceProvider(), signature)
would be
rsaRead.VerifyData(original, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1)
While it might not look simpler, it prevents the allocation and finalization of the SHA1CryptoServiceProvider that the other method did, and it sets up for The Future when you may want to switch from Pkcs1 signature padding to PSS signature padding. (But the real advantage is that method is on the RSA base class instead of the RSACryptoServiceProvider specific type).

RSA: Encrypt password in javascript but failed to decrypt that in C#

I want apply the RSA encryption to my project, but encountered some troubles:
First, I have download the JavaScripts library from
http://www.ohdave.com/rsa/ ,and add reference to my project;
Second, I have define the RSA object and code to initialize that:
internal RSACryptoServiceProvider Rsa
{
get
{
if (HttpContext.Cache["Rsa"] != null)
{
RSACryptoServiceProvider encryptKeys = (RSACryptoServiceProvider)HttpContext.Cache["Rsa"];
return encryptKeys;
}
else
{
return new RSACryptoServiceProvider(1024);
}
}
set
{
HttpContext.Cache.Remove("Rsa");
HttpContext.Cache.Insert("Rsa", value);
}
}
public ActionResult SignUp()
{
this.Rsa = Security.GetRsa();
RSAParameters param= this.Rsa.ExportParameters(true);
//this will bind to view
TempData["exponent"] = Util.BytesToHexString(param.Exponent);
TempData["key"] = Util.BytesToHexString(param.Modulus);
UserInfo user = new UserInfo();
user.Birthday = DateTime.Now.Date;
return View(user);
}
private RSACryptoServiceProvider GetRsa()
{
RSACryptoServiceProvider Rsa = new RSACryptoServiceProvider(1024);
return Rsa;
}
3.then, on JavaScript side , I have code, it encrypt the password user input and the bind it control:
var hash = document.getElementById("Pwd").value;
var exponent = document.getElementById("exponent").innerHTML;
var rsa_n = document.getElementById("key").innerHTML;
setMaxDigits(131);
var key = new RSAKeyPair(exponent, "", rsa_n);
hash = encryptedString(key, "111");
document.getElementById("Pwd").value = hash;
document.getElementById("Pwd2").value = hash;
document.getElementById("error").innerHTML = "";
document.getElementById("submit").click();
4.when user click submit, my C# code get the encrypted pwd string and try to decrypt it but failed with exception: bad data:
[HttpPost]
public ActionResult SignUp(UserInfo user)
{
user.UserId = user.UserId.ToLower(); //ignore case
user.UserGUID = Guid.NewGuid();
user.CreatedDate = DateTime.Now;
user.IsEnabled = false;
user.Pwd = Convert.ToBase64String(Rsa.Decrypt(Util.HexStringToBytes(user.Pwd), false));//Exception:Rsa.Decrypt throw bad data exception
who do you know how to fix it? thank you in advance.
I had a very similar problem in that most of the JavaScript based RSA encryption solutions wasn't "compatible" with .NET's implementation.
Almost all the implementations I found online had one or both of the following items causing the incompatibility with .NET's implementation.
The byte order encoding in JavaScript is different to the byte order that .NET used. This is a biggie as for example a string is represented with a different order of bytes in JS than it is in .NET so you'll need to convert before encrypting and after decrypting. I believe it's enough to just reverse the byte order to match .NET, but don't quote me on that.
Padding was different: .NET uses OAEP padding by default for RSA so the JS implementation of RSA should support the same padding too. I believe OAEP padding is also called PKCS#1 v2.0 padding, but don't quote me on that either.
Aside: I found an amazing JS library, called JavaScript.NET (from jocys.com) that mirrors tons of the .NET BCL functionality, including the RSA implementation, such that I could even use similar classes, properties and methods. Have a look at this. I can confirm it works with .NET RSA implementation. Give it a go - here are some links for it:
Jocys JS.NET Code Project demo
Jocys JS.NET Download
Hth

Can anyone give me an example of using BouncyCastle to import .pem public DSA key into c#?

I am trying co import a .pem key into c#, and I've found a library, which does that: BouncyCastle
I've created a code, which loads public key and is supposed to load the data into DSACryptoServiceProvider:
DSA dsa;
using (StreamReader rdr = new StreamReader(#"pubkey.pem"))
{
PemReader pr = new PemReader(rdr);
DsaPublicKeyParameters o = pr.ReadObject() as DsaPublicKeyParameters;
CspParameters prm = new CspParameters(13);
prm.Flags = System.Security.Cryptography.CspProviderFlags.UseMachineKeyStore;
//o.Parameters.
dsa = new DSACryptoServiceProvider(prm);
DSAParameters dp = new DSAParameters();
dp.G = o.Parameters.G.ToByteArray();
dp.P = o.Parameters.P.ToByteArray();
dp.Q = o.Parameters.Q.ToByteArray();
dp.Y = o.Y.ToByteArray();
if (o.Parameters.ValidationParameters != null)
{
dp.Counter = o.Parameters.ValidationParameters.Counter;
dp.Seed = o.Parameters.ValidationParameters.GetSeed();
}
//todo: missing: J, X?
dsa.ImportParameters(dp);
}
it crashes on dsa.ImportParameters(dp); with following exception: Cryptographic exception:bad data.
What should I change for this to work?
You need to use the ToByteArrayUnsigned method instead of plain ToByteArray one as otherwise there are cases where the byte array representation ends up with a leading zero byte which breaks everything :)

Bouncycastle: what does the subKeyID-Parameter of AddKeyTransRecipient do?

I'm trying to asymetrically encrypt a message of arbitrary length with bouncycastle. (1.4+ with C#)
This is the code I have right now. It is supposed to (but doesn't) generate a CMS message where the data itself is encrypted with AES256 with a random key and the key is encrypted with the public key from keyPair.
keyPair is an RSA-Key (RsaKeyParameters)
public static byte[] Encrypt(byte[] input, AsymmetricCipherKeyPair keyPair)
{
CmsEnvelopedDataGenerator generator = new CmsEnvelopedDataGenerator();
// those two lines are certainly wrong.
// I have no idea what the subKeyID parameter does
byte[] subKeyId = new byte[] {};
generator.AddKeyTransRecipient(keyPair.Public, subKeyId);
CmsProcessableByteArray cmsByteArray = new CmsProcessableByteArray(input);
CmsEnvelopedData envelopeData =
generator.Generate(cmsByteArray, CmsEnvelopedDataGenerator.Aes256Cbc);
return envelopeData.GetEncoded();
}
What is the subKeyId parameter in the Encrypt method for and what value does it need to have?
aaronls is being a little unfair to the author of "Beginning cryptography with Java", who after all wrote all the unit tests himself in the first place...
As other commenters have pointed out, CMS works with certificates, you can't just pass a public key; it must be possible to refer to the key either by "SubjectKeyIdentifier" or by "IssuerAndSerialNumber". The two alternatives of AddKeyTransRecipient allow this. If these terms don't mean anything to you, you probably need to do some background reading on X.509.
Look at the function TryKekAlgorithm in the EnvelopedDataTest.cs file of the BouncyCastle source. Instead of doing AddKeyTransRecipient, they are doing AddKekRecipient.
public static byte[] Encrypt(byte[] input, AsymmetricCipherKeyPair keyPair)
{
CmsEnvelopedDataGenerator generator = new CmsEnvelopedDataGenerator();
DerObjectIdentifier algOid = //initialize
//Still trying to figure out kekId here.
byte[] kekId = new byte[] { 1, 2, 3, 4, 5 };
string keyAlgorithm = ParameterUtilities.GetCanonicalAlgorithmName("AES256");
generator.AddKekRecipient(keyAlgorithm, keyPair.Public, kekId);
CmsProcessableByteArray cmsByteArray = new CmsProcessableByteArray(input);
CmsEnvelopedData envelopeData =
generator.Generate(cmsByteArray, CmsEnvelopedDataGenerator.Aes256Cbc);
return envelopeData.GetEncoded();
}
Edit: I think the kekId is just a unique identifier used to reference the key. Just a way to "name" the key. So you can have a book of keys, and each one has an identifier. When you send an encrypted message, the unencrypted key identifier tells you which of the keys was used to encrypt the message.
Here is a pretty good explanation of key identifiers on page 140:
[http://books.google.com/books?id=Pgg-Es2j3UEC&pg=PA140&lpg=PA140&dq=understanding+key+identifiers+encrypt&source=bl&ots=nFg0BzM2ht&sig=Ux5sreXMKyuEEZu0uaxE7cXC1VI&hl=en&ei=JKKJStbHGJivtgffsNznDA&sa=X&oi=book_result&ct=result&resnum=6#v=onepage&q=&f=false][1]
And here is another book that is using BouncyCastleCrypto, but it looks like they did little more than rip off the unit test source code. They have explained it a little:
[http://books.google.com/books?id=WLLAD2FKH3IC&pg=PA343&lpg=PA343&dq=CmsEnvelopedDataGenerator+AddKekRecipient&source=bl&ots=O9HinJm3yB&sig=K5Z99DIVWW4-0abPIFR7x4lzBhU&hl=en&ei=g6aJSrjeDuHktgennNjnDA&sa=X&oi=book_result&ct=result&resnum=6#v=onepage&q=CmsEnvelopedDataGenerator%20AddKekRecipient&f=false][2]
To use AES, it is not enough to use a AsymmetricCipherKeyPair.
You should use a X509 certificate, where the public key is signed by an certificate authority (CA).
the subKeyId is an attribute of the certificate, the subject Key Identifier:
(X509Certificate) cert.getSubjectUniqueID()
To encrypt a message of artrary length, you should use AES only to exchange a symmetric Keypassword and use this key for symmetric encryption.

System.Security.Cryptography and "Bad Data" - character encoding?

The class that produces "Bad Data" errors:
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace MyNameSpace
{
public class RSAcrypt
{
private string _encryptedData;
private string _decryptedData;
public string EncryptedData
{
get { return _encryptedData; }
set { _encryptedData = value; }
}
public string DecryptedData
{
get { return _decryptedData; }
set { _decryptedData = value; }
}
public RSAcrypt()
{
}
/// <param name="CryptAction"> The action to perform on the string {Encrypt|Decrypt} </param >
/// <param name="StringToCrypt"> A string to perform the Action on </param>
public RSAcrypt(string CryptAction, string StringToCrypt)
{
UnicodeEncoding thisUnicodeEncoding = new UnicodeEncoding();
RSACryptoServiceProvider thisRSACryptoServiceProvider = new RSACryptoServiceProvider();
byte[] _stringToCrypt = thisUnicodeEncoding.GetBytes(StringToCrypt);
switch (CryptAction)
{
case "Encrypt":
byte[] encryptedData = Encrypt(_stringToCrypt, thisRSACryptoServiceProvider.ExportParameters(false));
_encryptedData = thisUnicodeEncoding.GetString(encryptedData);
break;
case "Decrypt":
byte[] decryptedData = Decrypt(_stringToCrypt, thisRSACryptoServiceProvider.ExportParameters(true));
_decryptedData = thisUnicodeEncoding.GetString(decryptedData);
break;
default:
break;
}
}
static private byte[] Encrypt(byte[] DataToEncrypt, RSAParameters keyInfo)
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.ImportParameters(keyInfo);
return RSA.Encrypt(DataToEncrypt, false);
}
static private byte[] Decrypt(byte[] DataToDecrypt, RSAParameters keyInfo)
{
#region Temporary Assignment - Remove before build
byte[] tmpVal = null;
#endregion
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
try
{
RSA.ImportParameters(keyInfo);
#region Temporary Assignment - Remove before build
tmpVal = RSA.Decrypt(DataToDecrypt, false);
#endregion
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "Exception Thrown");
}
#region Temporary Assignment - Remove before build
return tmpVal;
#endregion
}
}
}
Is there anything that I can change in this class that would allow me to check the encoding prior to passing the byte array to Encrypt / Decrypt?
It seems like I have a reference around here somewhere, but I am becoming frustrated, so I thought it would at least help if I stopped to do something other than reading and compiling...
BTW, I am calling this class to write to a password to an XML file using the Nini initialization framework.
http://nini.sourceforge.net/manual.php#ASimpleExample
Also, I used Notepad2 to change the file encoding (UTF-8) before I wrote to the XML file.
That was after the program halted after I compiled the first time. Using the debugger, I was able to see that the encoding was different between the XML data in memory (UTF-8) and the data on disk (ANSI).
That does not appear to be the case now, but the program still halts, referencing bad data returned from the Decrypt portion of RSAcrypt().
(also note that Encrypt and Decrypt were identical methods before my frustration set in, they do function the same, but I wanted to try to capture addition exception information related to the bad data claim. Of course, you will notice that I allowed my frustration to handicap my code ;-) )
Any suggestions, ideas or references would be great.
TIA,
E
Inside your constructor you generate a new RSA keypair each time when you do:
RSACryptoServiceProvider thisRSACryptoServiceProvider = new RSACryptoServiceProvider();
Since your constructor is where you encrypt and decrypt, you are encrypting with an RSA Key, and decrypting with a completely different one.
To make this work, you have several options based on how you plan to use your code.
One option is to export the RSA key, and use that for all encryption/decryption operations. This is the only option if you plan on decrypting/encrypting data between different runs of your executable.
Of course this completely glosses over how you will store your public/private key (I recommend DPAPI on windows), for use by your application.

Categories

Resources