Edit: Thanks to the advice from Lasse Vågsæther Karlsen. I was able to solve my problem. I used Bitconverter to convert bytes to a string and then used UTF8.GetBytes to convert them back to bytes. This doesn't work. I decided to use
Convert.FromBase64String
Convert.ToBase64String
I'm trying to implement RSA into a Client-Server C# Program.
My Plan is to generate a public key on the server and send it to the client during the handshake. The client will then generate an AES Key that is encrypted with the RSA public key and send it back to the server. I will then use AES to encrypt communication during the session.
The problem is that, when the Server receives the encrypted Message, I get an error that says the file exceeds limitations. Even though the encrypted message on the client and when the service receives it are the same length and have the same content if I convert them into an XML string to compare the 2.
error: System.Security.Cryptography.CryptographicException: The data to be decrypted exceeds the maximum for the module by 256 bytes.
Sending serialized public key to client:
RSAManager rSAManager = new RSAManager();
string publicKeyString = SerializeKey(rSAManager.publicKey); // Serialize the public key so we can send it to the clients
// Send test data to the remote device.
Send(client, $"{publicKeyString}!");
The RSAManager Class:
public class RSAManager
{
#region Keys, Containername, Keysizes
public RSAParameters publicKey;
public RSAParameters privateKey;
static string CONTAINER_NAME = "MyContainerName";
public enum KeySizes
{
SIZE_512 = 512,
SIZE_1024 = 1024,
SIZE_2048 = 2048,
SIZE_952 = 952,
SIZE_1369 = 1369
};
#endregion
#region Methods
public RSAManager()
{
GenerateKeys();
}
public void GenerateKeys()
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false; //Don't store the keys in a key container
publicKey = rsa.ExportParameters(false);
privateKey = rsa.ExportParameters(true);
}
}
/// <summary>
/// Encrypts the given byte array with the RSA standard
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public byte[] Encrypt(string message)
{
byte[] input = Encoding.UTF8.GetBytes(message);
byte[] encrypted;
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
rsa.ImportParameters(publicKey);
encrypted = rsa.Encrypt(input, true);
}
return encrypted;
}
/// <summary>
/// Decrypts the given byte array with the RSA standard
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public string Decrypt(byte[] encrypted)
{
byte[] decrypted;
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
rsa.ImportParameters(privateKey);
decrypted = rsa.Decrypt(encrypted, true);
}
return Encoding.UTF8.GetString(decrypted);
}
Code used to serialize and deserialize:
Serialize:
static string SerializeKey(RSAParameters publicKey)
{
string publicKeyString;
{
//we need some buffer
var sw = new System.IO.StringWriter();
//we need a serializer
var xs1 = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//serialize the key into the stream
xs1.Serialize(sw, publicKey);
//get the string from the stream
publicKeyString = sw.ToString();
}
return publicKeyString;
}
Deserialize:
static RSAParameters DeSerializeKey(string publicKeyString)
{
var sr = new System.IO.StringReader(publicKeyString);
//we need a deserializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//get the object back from the stream
return (RSAParameters)xs.Deserialize(sr);
}
Receiving, Encyrypting and sending back to client
string publicKeyString = TrimString(new string[] {"!"},content);
RSAManager rSAManager = new RSAManager();
rSAManager.publicKey = DeSerializeKey(publicKeyString);
string randomAESKey = GetRandomString(40);
Console.WriteLine($"Randomstring: {randomAESKey");
byte[] encrypted = rSAManager.Encrypt(randomAESKey);
string encryptedAESKey = BitConverter.ToString(encrypted);
Console.WriteLine($"Encrypted. {encryptedAESKey}");
Console.WriteLine("Length of encrypted string: " + encryptedAESKey.Length);
// Echo the data back to the server.
Send(handler, encryptedAESKey);
Server Receiving and Decrypting the AES KEY
// Write the response to the console.
Console.WriteLine("Length of encrypted response: " + response.Length);
Console.WriteLine("Length of public Key: " + SerializeKey(rSAManager.publicKey).Length);
// Decrypt functions needs byte array so we need to encode it. This line always causes the error.
string encryptedResponse = rSAManager.Decrypt(Encoding.UTF8.GetBytes(response));
// Received encrypted response
Console.WriteLine($"Decrypted response: {encryptedResponse}");
The maximum size of data that can be encrypted with RSA is 245, what you're supposed to do is encrypt the main block with a randomly generated symmetric key and encrypt that key with your private key.
This link on StackExchange has some more info.
Any reason why you are using BitConverter while getting a string back from encrypted bytes?
Did you try using Encoding.UTF8.GetString?
I strongly recommend that you consider using libsodium for this kind of problem. Their explicit goal is to provider a better API for cryptographic operations to make it less likely that you will screw up your security by misusing the library.
Also, have you also considered how you are going to authenticate the server? You might not need a newly generated RSA key.
Related
In my application I need to encrypt various settings and a password.
So far I have been doing this with the RijndaelManaged class etc. as seen here:
/// <summary>
/// Encrypts the string defined by parameter "data" and returns the encrypted data as string
/// </summary>
/// <param name="data">Data to be encrypted</param>
/// <returns>The encrypted data</returns>
public static string Encrypt(string data)
{
if (data == "")
return "";
byte[] bytes = Encoding.ASCII.GetBytes(initVector);
byte[] rgbSalt = Encoding.ASCII.GetBytes(saltValue);
byte[] buffer = Encoding.UTF8.GetBytes(data);
byte[] rgbKey = new PasswordDeriveBytes(passPhrase, rgbSalt, hashAlgorithm, passwordIterations).GetBytes(keySize / 8);
RijndaelManaged managed = new RijndaelManaged();
managed.Mode = CipherMode.CBC;
ICryptoTransform transform = managed.CreateEncryptor(rgbKey, bytes);
MemoryStream memStream = new MemoryStream();
CryptoStream cryStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
cryStream.Write(buffer, 0, buffer.Length);
cryStream.FlushFinalBlock();
byte[] inArray = memStream.ToArray();
memStream.Close();
cryStream.Close();
return Convert.ToBase64String(inArray);
}
The usual problem is that I need to store the passPhrase (and saltValue) somewhere.
To store the passPhrase in a sequre way I came across the DPAPI Protect() and Unprotect() classes as seen here:
/// <summary>
/// Use Windows' "Data Protection API" to encrypt the string defined by parameter "clearText".
/// To decrypt, use the method "Unprotect"
/// http://www.thomaslevesque.com/2013/05/21/an-easy-and-secure-way-to-store-a-password-using-data-protection-api/
/// </summary>
/// <param name="clearText"></param>
/// <param name="optionalEntropy"></param>
/// <param name="scope"></param>
/// <returns></returns>
public static string Protect(string clearText, string optionalEntropy = null, DataProtectionScope scope = DataProtectionScope.CurrentUser)
{
if (clearText == null)
throw new ArgumentNullException("The parameter \"clearText\" was empty");
byte[] clearBytes = Encoding.UTF8.GetBytes(clearText);
byte[] entropyBytes = string.IsNullOrEmpty(optionalEntropy) ? null : Encoding.UTF8.GetBytes(optionalEntropy);
byte[] encryptedBytes = ProtectedData.Protect(clearBytes, entropyBytes, scope);
return Convert.ToBase64String(encryptedBytes);
}
My question is the following:
With the DPAPI I can now store the passPhrase for my encryption method in a secure way, but why shouldn’t I simply use the DPAPI to encrypt all my setting directly?
Would this fill up the DPAPI with an amount of data, that it is not meant for?
My idea was instead of doing the following:
string setting1 = ”mySettingValue1”;
StoreSettingSomewhere(Encrypt(setting1));
I could do the following:
string setting1 = ”mySettingValue1”;
StoreSettingSomewhere(Protect(setting1, bla bla bla));
I know that when using DPAPI I must decrypt on the same machine (or with the same user), but this would not be a problem in my case.
Any help is appreciated!
The Data Protection API hands you back an opaque blob that is the encrypted (and salted, and hashed) result of what you wanted encrypted.
You cannot "fill up" the DP API - you would only "fill up" yourself (as the blobs are somewhat large; but they do internally contain everything need to later verify the encrypted data).
The down-side of the Data Protection API is that you have to be logged in as the user; and you cannot share settings between users (unless you used the Machine-wide scope).
I am trying to encrypt a message using RSA public key and decrypt it using my private key. It encrypted the message, but I was not able to decrypt it. The message was still encrypt after the final process. When I exported the private key, it also included the public keys. I tried to remove the public key leaving, but it would not work.
Here are the private and public keys
//This is the public key
private const string public_key = "<RSAKeyValue><Modulus>uznzVPilsR1rWPkpq6m6IALaafDnVZTDDcnEyBD3A/PBx2JZTKM0DTgiTDDwCEmQBNBpPILcIBdtg3aSUgicair+2ksYrVFT+uiy0Zy1nU6qoJ+SsapLKrpCa1zHpV4LMO/pFo4Foqzw0C1FNe56FXo1xj77GPgeYl0MHUVtAUc=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
//This is the private and public key.
private const String private_key = "<RSAKeyValue><Modulus>uznzVPilsR1rWPkpq6m6IALaafDnVZTDDcnEyBD3A/PBx2JZTKM0DTgiTDDwCEmQBNBpPILcIBdtg3aSUgicair+2ksYrVFT+uiy0Zy1nU6qoJ+SsapLKrpCa1zHpV4LMO/pFo4Foqzw0C1FNe56FXo1xj77GPgeYl0MHUVtAUc=</Modulus><Exponent>AQAB</Exponent><P>+jPKs9JxpCSzNY+YNanz49Eo/A6RaU1DZWoFm/bawffZOompeL1jzpUlJUIrKVZJkNFvlxE90uXVwjxWBLv9BD==</P><Q>v5CVWKZ5Wo7W0QyoEOQS/OD8tkKS9DjzZnbnuo6lhcMaxsBrCWLstac1Xm2oFNtZgLtrPGbPfCNC5Su4Rz/P5w==</Q><DP>ZnyikmgobqEt20m3gnvcUDxT+nOJMsYYTklQhONoFj4M+EJ9bdy+Lle/gHSLM4KJ3c08VXgVh/bnSYnnfkb20Q==</DP><DQ>sSYGRfWk0W64Dpfyr7QKLxnr+Kv186zawU2CG44gWWNEVrnIAeUeWxnmi41CWw9BZH9sum2kv/pnuT/F6PWEzw==</DQ><InverseQ>XpWZQKXa1IXhF4FX3XRXVZGnIQP8YJFJlSiYx6YcdZF24Hg3+Et6CZ2/rowMFYVy+o999Y5HDC+4Qa1yWvW1vA==</InverseQ><D>Kkfb+8RrJqROKbma/3lE3xXNNQ7CL0F5CxQVrGcN8DxL9orvVdyjlJiopiwnCLgUHgIywceLjnO854Q/Zucq6ysm2ZRq36dpGLOao9eg+Qe8pYYO70oOkEe1HJCtP1Laq+f3YK7vCq7GkgvKAI9uzOd1vjQv7tIwTIADK19ObgE=</D></RSAKeyValue>";
//Encrypting the text using the public key
private RSACryptoServiceProvider cipher = null;
cipher = new RSACryptoServiceProvider();
cipher.FromXmlString(public_key);
byte[] data = Encoding.UTF8.GetBytes(txtUnencrypt.Text);
byte[] cipherText = cipher.Encrypt(data, false);
lblUnencryptMessage.Text = Convert.ToBase64String(cipherText);
// decryptText();
//Trying to decrypt the text using the private key
cipher = new RSACryptoServiceProvider();
cipher.FromXmlString(private_key);
byte[] ciphterText = Convert.FromBase64String(lblUnencryptMessage.Text);
byte[] plainText = cipher.Decrypt(ciphterText, false);
lblDecript.Text = Convert.ToBase64String(plainText);
For example, I encrypted the word "Testing", the encrypted text was
kkqs+UGHNI7/3cKhQvSnJrKzNeCBQX9xHX2VrlyMvnwtszJAoFuViBZlfwmpVhqddnVUrlaqqkD7971E8L3wWltfGetK9nIljeo0GeietLYljoY0Gy3gatU++JPrqajAKxpIB75tvVlKXuYIs0qE3XWZu9bj0zAa4BVT2MhVNQM="
The decrypted text was
dGVzdGluZw==
What am I missing here?
There appears to be nothing wrong with the encryption/decryption code, just how you're handling the decrypted data. Specifically this line:
lblDecript.Text = Convert.ToBase64String(plainText);
You are taking the decrypted data and Base64 encoding it, which is why you get: dGVzdGluZw== (since this is the Base64 encoded version of the string "testing").
You need to use the following instead:
lblDecript.Text = Encoding.UTF8.GetString(plainText);
This should correctly convert the decrypted byte array to a the original string.
I have looked online for what this exception means in relation to my program but can't seem to find a solution or the reason why its happening to my specific program.
C#.Net code:
/// Decrypts a BASE64 encoded string of encrypted data, returns a plain string
/// </summary>
/// <param name="base64StringToDecrypt">an Aes encrypted AND base64 encoded string</param>
/// <param name="passphrase">The passphrase.</param>
/// <returns>returns a plain string</returns>
public static string AESDecrypt(string base64StringToDecrypt, string passphrase)
{
//Set up the encryption objects
using (AesCryptoServiceProvider acsp = GetProvider(Encoding.Default.GetBytes(passphrase)))
{
byte[] RawBytes = Convert.FromBase64String(base64StringToDecrypt);
ICryptoTransform ictD = acsp.CreateDecryptor();
//RawBytes now contains original byte array, still in Encrypted state
//Decrypt into stream
MemoryStream msD = new MemoryStream(RawBytes, 0, RawBytes.Length);
CryptoStream csD = new CryptoStream(msD, ictD, CryptoStreamMode.Read);
//csD now contains original byte array, fully decrypted
//return the content of msD as a regular string
return (new StreamReader(csD)).ReadToEnd();
}
}
I have use google CryptoJS 3.1 to encrypt password
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");
</script>
My JavaScript code :
var encrypted = CryptoJS.AES.encrypt(newPassword, oldPassword);
cipherText1 = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
console.log(cipherText1);
Try replacing your code with following
var encrypted = CryptoJS.AES.encrypt(newPassword, oldPassword);
cipherText1 = Convert.ToBase64String(encrypted);
console.log(cipherText1);
I have a server written in Java which sends converts its RSA key to the XML format used by .NET before sending it to the client:
public String getPublicKeyXML() {
try {
KeyFactory factory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec publicKey = factory.getKeySpec(this.keyPair.getPublic(), RSAPublicKeySpec.class);
byte[] modulus = publicKey.getModulus().toByteArray();
byte[] exponent = publicKey.getPublicExponent().toByteArray();
String modulusStr = Base64.encodeBytes(modulus);
String exponentStr = Base64.encodeBytes(exponent);
String format =
"<RSAKeyValue>" +
"<Modulus>%s</Modulus>" +
"<Exponent>%s</Exponent>" +
"</RSAKeyValue>";
return String.format(format, modulusStr, exponentStr);
} catch (Exception e) {
this.server.logException(e);
return "";
}
}
The client, written in C#, then loads the key and uses it to encrypt a 256 bit AES key:
public static byte[] encrypt(string xmlKey, byte[] bytes)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlKey);
byte[] cipherBytes = rsa.Encrypt(bytes, false);
rsa.Clear();
return cipherBytes;
}
The server is then supposed to decrypt the AES key using its private RSA key:
public byte[] decrypt(byte[] data) {
try {
PrivateKey privateKey = this.keyPair.getPrivate();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
} catch (Exception e) {
this.server.logException(e);
return new byte[0];
}
}
However, the server fails with an error stating "Data must not be longer than 384 bytes." Looking at the data to be decrypted, I noticed that it's 385 bytes. I tried increasing the RSA key length, and now the server tells me the data must be no longer than 512 bytes, while the encrypted data from the client is 513 bytes. Why is the encrypted data always one byte longer than expected?
EDIT:
Here's a sample XML-formatted key as is transmitted from the server to the client:
<RSAKeyValue><Modulus>ANsMd2dCF6RsD5v5qjlHEjHm0VWD99gSYHP+pvyU8OgNL9xM5+o+yMAxWISOwMii9vJk1IzYGf18Fj2sMb5BsInlG2boZHb6KHh7v8ObPa4MuwB/U63i8AVU3N/JTugaPH0TKvo1WNUooXEHT23nOk+vh1QipzgKQYGl68qU35vKmpNAa79l1spXA66LckTWal4art9T08Rxgn9cMWujlF+wh9EQKQoxxgj4gCoXWRDTFYjRo/Mp5xDPwNjloTs/vFCPLvY7oI+lVrHhrPyz1R473ZuEhZm+rSeGBcY9I8vhg0AIixN7KYBLhrIecmqoNZHi6LohjD2F9zhdLaTU0IIU8eeKpbEZ5eB1kYngMONBq3A/IoG0Qa/7EcSAMMspBEObffK9kCNzvnbFg5wLuy8EHNaK3nmnuTppgCwCyNqZyHeAbZaUBjNguLhHtqkHFiPJ063Xesj9UbSsCmlBliGTDXWfeJANnjGP6D3R+uLXVy9SZe+cY92JW3eZA2k//w==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
I have verified that the data sent is the same as the data being received.
Knocking off the last byte results in a BadPaddingException. I also tried knocking off the first byte, with the same result.
I found the problem. The BigInteger's toByteArray() function included a leading zero for some reason. I just removed the leading zeros from the array and it now works like a charm!
This will not fix the problem (I tested it to no avail), but I wanted to call to your attention that RSACryptoServiceProvider implements the IDisposable interface and therefore should be properly disposed of when complete. Your C# encrypt method can be written a bit better (and more concise!) as such:
public static byte[] encrypt(string xmlKey, byte[] bytes)
{
using (var rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(xmlKey);
return rsa.Encrypt(bytes, false);
}
}
I'm having a problem setting up RSA encryption/decryption mechanism between flex client and web service written in c#. The idea is this: I'll encrypt some text from flex and then decrypt it from web service. I'm using as3crypto library from google. It is encrypting/decrypting text properly. I also have the code on the web service side to encrypt/decrypt properly. My problem is synchronizing them - basically sharing the public key to flex and keeping the private key to the web service.
My flex "encrypt" function takes modulus and exponent of RSA to do text encryption, so how do i get these modulus and exponent attributes from the web service's RSACryptoServiceProvider, so they speak the same standard.
I tried the
RSAKeyInfo.Modulus
RSAKeyInfo.Exponent
from the web service and fed them to the flex client.
After doing encryption on flex I took the cipher text and fed it to decrypt method on web service, but it is giving me "bad data" error message.
System.Security.Cryptography.CryptographicException: Bad Data.
at System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr)
at System.Security.Cryptography.Utils._DecryptKey(SafeKeyHandle hPubKey, Byte[] key, Int32 dwFlags)
at System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[] rgb, Boolean fOAEP)
at Microsoft.Samples.Security.PublicKey.App.RSADecrypt(Byte[] DataToDecrypt, RSAParameters RSAKeyInfo, Boolean DoOAEPPadding) in C:\Users
\Me\Desktop\After Release\5-24-2011-webServiceCrypto\publickeycryptography\CS\PublicKeyCryptography\PublicKey.cs:line 219
Encryption failed.
How do i make sure they are both using the same byte 64 or 128 byte encryption . ie the input from flex should fit to what is expected by the web service RSACryptoServiceProvider's decrypt method.
(I'm assuming the size might be a problem, may be it's not - i'm lost)
Here is the code, first flex client followed by web service c# code
private function encrypt():void {
var rsa:RSAKey = RSAKey.parsePublicKey(getModulus(), getExponent());
trace("Modulus Lenght: " + getModulus().length);
trace("Exponent Lenght : " + getExponent().length);
var data:ByteArray = getInput(); //returns byteArray of plainText
var dst:ByteArray = new ByteArray;
rsa.encrypt(data, dst, data.length);
trace("Enc Data: " + dst.toString() );
currentResult = Hex.fromArray(dst);
encryptedText = currentResult;
trace("Encrypted:: " + currentResult);
}
//For testing purposes
private function decrypt():void {
var rsa:RSAKey = RSAKey.parsePrivateKey(getModulus(), getExponent(), getPrivate(), getP(), getQ(), getDMP1(), getDMQ1(), getCoeff());
var data:ByteArray = Hex.toArray(encryptedText);
trace("Byte array: " + data.toString());
var dst:ByteArray = new ByteArray;
rsa.decrypt(data, dst, data.length);
decryptedText = Hex.fromArray(dst);
trace("Decrypted text: " + Hex.toString(decryptedText));
}
And web service part is as follows:
try
{
//Create a UnicodeEncoder to convert between byte array and string.
UnicodeEncoding ByteConverter = new UnicodeEncoding();
//Create byte arrays to hold original, encrypted, and decrypted data.
byte[] dataToEncrypt = ByteConverter.GetBytes("Data to Encrypt");
byte[] encryptedData;
byte[] decryptedData;
//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
//Pass the data to ENCRYPT, the public key information
//(using RSACryptoServiceProvider.ExportParameters(false),
//and a boolean flag specifying no OAEP padding.
encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false);
//Pass the data to DECRYPT, the private key information
//(using RSACryptoServiceProvider.ExportParameters(true),
//and a boolean flag specifying no OAEP padding.
decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false);
//Display the decrypted plaintext to the console.
Console.WriteLine("\n\nDecrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
}
}
static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
try
{
byte[] encryptedData;
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
//Import the RSA Key information. This only needs
//toinclude the public key information.
RSA.ImportParameters(RSAKeyInfo);
//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
return encryptedData;
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
try
{
Console.WriteLine("Modulus Lenghth :" + RSAKeyInfo.Modulus.Length);
Console.WriteLine("Exponent Length :" + RSAKeyInfo.Exponent.Length);
byte[] decryptedData;
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAKeyInfo);
//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
return decryptedData;
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
{
Console.WriteLine(e.ToString());
return null;
}
}
I'm not quite sure if this RSA set up is the way to go...
Any kinda comment / advice/ or recommended solution is welcome,
thanks guys
Eureka! Eureka! I got it.
The problem was after decryption from web service, the encrypted byte array missed 0's in between, so that when changed to string it gets unreadable '????????' text. So I just put paddWithZeros() function to pad the decrypted byte array with 0's between bytes and it worked.
Thanks Kevin, your solution gave me an insight into what things I should consider. So during decrypting I specify parameter fOAEP as false, so it would use PKCS#1 for padding (making both libraries use the same standard).
RSA.Decrypt(DataToDecrypt, DoOAEPPadding); // DoOAEPPadding = false
another error that i was getting is Bad Data exception. This was fixed when i shared the RSA cryptoServiceProvider's parameters (modulus and exponent) to actionScript methods.
I also changed the byte[] array of c# RSA attributes (like Modulus n, Exponent e, Private d..etc) to hexa string so that I'd be able to share with as3crypto library.
I'd love to share what worked for me; save others some time.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
import com.hurlant.crypto.Crypto;
import com.hurlant.crypto.rsa.RSAKey;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.crypto.symmetric.IPad;
import com.hurlant.util.Hex;
private var currentResult:String;
private var encryptedText:String;
private var decryptedText:String;
private function encrypt(plainText:String):String {
var rsa:RSAKey = RSAKey.parsePublicKey(getModulus(), getExponent());
var data:ByteArray = Hex.toArray(Hex.fromString(plainText)); //returns byteArray of plainText
var dst:ByteArray = new ByteArray;
rsa.encrypt(data, dst, data.length);
currentResult = Hex.fromArray(dst);
encryptedText = currentResult;
trace ("Cipher: " + currentResult);
return currentResult;
}
private function getInput():ByteArray {
return null;
}
private function getModulus():String {
return "b6a7ca9002b4df39af1ed39251a5d"; //read this value from web service.
}
private function getExponent():String {
return "011"; //read this value from web service.
}
//For debugging and testing purposes
// private function decrypt(cipherText:String):String {
// var rsa:RSAKey = RSAKey.parsePrivateKey(getModulus(), getExponent(), getPrivate(), getP(), getQ(), getDMP1(), getDMQ1(), getCoeff());
// var data:ByteArray = Hex.toArray(cipherText);
// var dst:ByteArray = new ByteArray;
// rsa.decrypt(data, dst, data.length);
// decryptedText = Hex.fromArray(dst);
//trace('decrypted : ' + decryptedText);
// return Hex.toString(decryptedText);
// }
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:VBox >
<s:Button label="Encrypt Text" click="encrypt('my plain text')" />
<s:Button label="Decrypt Text" click="decrypt({encryptedText})" />
</mx:VBox>
</s:Application>
And the web service part of decryption looks like this:
static public string RSADecrypt(string cipherText)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] DataToDecrypt = StringToByteArray(cipherText);
bool DoOAEPPadding = false;
try
{
byte[] decryptedData;
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
KeyInfo keyInfo = new KeyInfo();
RSAParameters RSAKeyInfo = keyInfo.getKey();
RSA.ImportParameters(RSAKeyInfo);
decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
byte[] paddedOutput = paddWithZeros(decryptedData); //to sync with as3crypto
return (ByteConverter.GetString(paddedOutput));
}catch (CryptographicException e)
{
//handle error
return null;
}
}
I'll do some reading about padding schemes for RSA, see if there is any misconception.
Thanks
Seems overly complicated. I've worked on some high security systems before, but this is ludicrous. Why would you need this kind of level of encryption at the text being sent unless you don't want the user to know the text he just inputted?
Just use a strong SSL key (256bit is max for IE6, you could use 512 but only compatible with newer browsers) for the actual transfer protocol (I imagine HTTP) with a binary data format (AMF) and everything should be fine. I doubt your system is that important to leverage the use of encrypting text.
I use as3crypto and JAVA web-services. Here are some thoughts:
a. I generated my public and private RSA keys via openssl
b. My client loads the public .cer file at application startup (if you just hardcoded them in from the generated key that works too).
var pemString : String = new String(data.target.data);
var x509Cert : X509Certificate = new X509Certificate(pemString);
var publicRSAKey : RSAKey = x509Cert.getPublicKey();
c. Encrypt my strings via
var inputByteArray : ByteArray = Hex.toArray(Hex.fromString(inputString));
var outputByteArray : ByteArray = new ByteArray();
appSettingsModel.publicRSAKey.encrypt(inputByteArray, outputByteArray, inputByteArray.length);
d. I didn't write the JAVA side of things but you aren't using JAVA anyways. I know that as3crypto uses PKCS1 padding by default:
RSAKEY.as
private function _encrypt(op:Function, src:ByteArray, dst:ByteArray, length:uint, pad:Function, padType:int):void {
// adjust pad if needed
if (pad==null) pad = pkcs1pad;
This can be changed but I haven't tried it yet. Based on your code it looks like you might be trying to decrypt with OAEP scheme, but I can't tell how you are setting that bool. You may want to take a look at what padding scheme is being used with the bool as false and try to change one side or the other to match padding strategies.