У меня проблема с настройкой механизма шифрования / дешифрования RSA между гибким клиентом и веб-службой, написанной на C #. Идея такова: я зашифрую какой-то текст из flex, а затем расшифрую его из веб-службы. Я использую библиотеку as3crypto от Google. Он правильно шифрует / дешифрует текст. У меня также есть код на стороне веб-службы для правильного шифрования / дешифрования. Моя проблема заключается в их синхронизации - в основном, я делюсь открытым ключом для гибкости и сохраняю закрытый ключ для веб-службы.
Моя функция flex «encrypt» принимает модуль и показатель степени RSA для шифрования текста, поэтому как мне получить эти атрибуты модуля и экспоненты из RSACryptoServiceProvider веб-службы, чтобы они говорили о том же стандарте. Я попробовал RSAKeyInfo.Modulus RSAKeyInfo.Exponent из веб-службы и отправил их гибкому клиенту. После выполнения шифрования на гибком диске я взял зашифрованный текст и отправил его для дешифрования метода в веб-службе, но он выдает мне сообщение об ошибке «неверные данные».
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.
Как убедиться, что они оба используют одинаковое 64- или 128-байтовое шифрование. т.е. ввод от flex должен соответствовать тому, что ожидается от метода дешифрования веб-службы RSACryptoServiceProvider. (Я предполагаю, что размер может быть проблемой, может быть, это не так - я потерялся)
Вот код, первый гибкий клиент, за которым следует код С # веб-службы
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));
}
А часть веб-сервиса выглядит следующим образом:
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;
}
}
Я не совсем уверен, подходит ли эта настройка RSA ... Любые комментарии / советы / рекомендуемые решения приветствуются, спасибо, ребята