ArgumentOutOfRangeException when calling X509Certificate2 - c#

I tried create a X509Certificate2 object with a public rsa key for encryption in Unity with c#. I get the following exception:
> ArgumentOutOfRangeException: Cannot be negative.
> Parameter name: length
> System.String.Substring (Int32 startIndex, Int32 length) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/String.cs:348)
> Mono.Security.X509.X509Certificate.PEM (System.String type, System.Byte[] data) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/Mono.Security.X509/X509Certificate.cs:601)
.
static loadKey() {
//get rsa public key
byte[] data = GetBytes("MIIBIjANBgkqhk......EuH+zIXFzvirHQ2AxE/5wIDAQAB");
Debug.Log(data.Length);
X509Certificate2 x509certificate = new X509Certificate2(data);
//[...]
}
This is the GetBytes function
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
For the record: data.Length is 784
Any ideas?

Thanks for your help. A certificate is defenately not a key so i finally managed to get a working function to encrypt a string with bouncycastle:
static string Encrypt2(string publicKeyFileName, string inputMessage)
{
try
{
// Converting the string message to byte array
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
byte[] inputBytes = enc.GetBytes(inputMessage);
AsymmetricKeyParameter publicKey = ReadAsymmetricKeyParameter(publicKeyFileName);
// Creating the RSA algorithm object
IAsymmetricBlockCipher cipher = new Pkcs1Encoding(new RsaEngine());
// Initializing the RSA object for Encryption with RSA public key. Remember, for encryption, public key is needed
cipher.Init(true, publicKey);
//Encrypting the input bytes
byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputBytes.Length);
return Convert.ToBase64String(cipheredBytes);
}
catch (Exception ex)
{
// Any errors? Show them
Debug.Log("Exception encrypting file! More info:");
Debug.Log(ex.Message);
}
return "";
}
public static 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;
}

Related

C# RSA Decrypt (The parameter is incorrect)

Im using the following code to encrypt and decrypt a small file using RSA and safely transfer them using usb drive (I know, RSA is not the best for encrypting files...)
But for some reason it wont work anymore. Im trying to decrypt my file and it keeps throwing a "The parameter is incorrect" exception
The keys did not changed (both private and public)
The code did not changed (both encrypt and decrypt)
Anybody have an idea of what could be wrong?
static int SegmentLength = 213; //85; // keysize/8 -42 -1
public static byte[] EncryptRSA(string publicKey, byte[] data)
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(2048, cspParams);
rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey));
//byte[] plainBytes = data;
//byte[] encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
var length = data.Length / SegmentLength + 1;
MemoryStream stream = new MemoryStream();
for (var i = 0; i < length; i++)
{
int lengthToCopy;
if (i == length - 1 || data.Length < SegmentLength)
lengthToCopy = data.Length - (i * SegmentLength);
else
lengthToCopy = SegmentLength;
//var segment = decryptedData.Substring(i * SegmentLength, lengthToCopy);
byte[] segment = new byte[lengthToCopy];
Buffer.BlockCopy(data, i * SegmentLength, segment, 0, lengthToCopy);
byte[] encrypted = rsaProvider.Encrypt(segment,false);
stream.Write(encrypted,0,encrypted.Length);
}
return stream.ToArray();
}
private const int EncryptedLength = 256; //keylen * 8
public static byte[] DecryptRSA(string privateKey, byte[] data)
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(2048, cspParams);
rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey));
var rsainfo = rsaProvider.ExportParameters(true);
var length = data.Length / EncryptedLength;
MemoryStream stream = new MemoryStream();
for (var i = 0; i < length; i++)
{
byte[] segment = new byte[EncryptedLength];
Buffer.BlockCopy(data, i * EncryptedLength, segment, 0, EncryptedLength);
byte[] decrypted = rsaProvider.Decrypt(segment, false);
stream.Write(decrypted, 0, decrypted.Length);
}
//string plainText = Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length);
return stream.ToArray();
}
System.Security.Cryptography.CryptographicException occurred
HResult=0x80070057 Message=Parâmetro incorreto.
Source=mscorlib StackTrace: at
System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32
hr) at
System.Security.Cryptography.RSACryptoServiceProvider.DecryptKey(SafeKeyHandle
pKeyContext, Byte[] pbEncryptedKey, Int32 cbEncryptedKey, Boolean
fOAEP, ObjectHandleOnStack ohRetDecryptedKey) at
System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[]
rgb, Boolean fOAEP) at Decriptor.Program.DecryptRSA(String
privateKey, Byte[] data) in
Program.cs:line 149
at Decriptor.Program.Main(String[] args) in
Program.cs:line 45
rsainfo {System.Security.Cryptography.RSAParameters} System.Security.Cryptography.RSAParameters
D {byte[256]} byte[]
DP {byte[128]} byte[]
DQ {byte[128]} byte[]
Exponent {byte[3]} byte[]
InverseQ {byte[128]} byte[]
Modulus {byte[256]} byte[]
P {byte[128]} byte[]
Q {byte[128]} byte[]

AES Encryption Windows Phone 8.1

I need to do 128 bit AES encryption on an application in Windows Phone 8.1. I used the following code for Encrypting and Decrypting the data respectively:
private string GetEncryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Encoding.UTF8.GetBytes(content);
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, null);
return Encoding.UTF8.GetString(cipherText, 0, cipherText.Length);
}
private string GetDecryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Encoding.UTF8.GetBytes(content);
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Decrypt(key, data, null);
return Encoding.UTF8.GetString(cipherText, 0, cipherText.Length);
}
But the encryption and decryption doesn't seem to be working properly. It is getting encrypted to some unicode characters and throwing a crash on decrypting:
Length is not a multiple of block size and no padding is
selected.\r\nParameter name: ciphertext
What am I doing wrong here? Can someone please help?
EDIT
After a lot more time with Google, I found the following methods for encryption and decryption, but they doesn't seem to work either.
public string GetEncryptedContent(string input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
CryptographicHash Hash_AES = HAP.CreateHash();
string encrypted = "";
try
{
byte[] hash = new byte[32];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(pass)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(input));
encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));
return encrypted;
}
catch (Exception ex)
{
return null;
}
}
public string GetDecryptedContent(string input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
CryptographicHash Hash_AES = HAP.CreateHash();
string decrypted = "";
try
{
byte[] hash = new byte[32];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(pass)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
byte[] Decrypted;
CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
decrypted = Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
return decrypted;
}
catch (Exception ex)
{
return null;
}
}
EDIT 2
Finally managed to get the encryption working properly, but the decryption is still not working presumably because the encoding I am passing is not the right one:
private string GetEncryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Encoding.UTF8.GetBytes(content);
byte[] iv = new byte[128 / 8]; // Adding this solved the encryption issue.
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, iv);
return Convert.ToBase64String(cipherText);
}
private string GetDecryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Convert.FromBase64String(content); // Believe this is where the issue is, but not able to figure it out.
byte[] iv = new byte[128 / 8]; // Added this to make the decryption work the same way.
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Decrypt(key, data, iv);
return Convert.ToBase64String(cipherText);
}
I finally solved the problem. The problem was with the text encoding. Using the correct encoding solved the issue. The working code below:
public static string EncryptAES(string content, string password)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(password);
byte[] data = Encoding.UTF8.GetBytes(content);
byte[] iv = new byte[keyMaterial.Length];
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, iv);
return Convert.ToBase64String(cipherText);
}
public static string DecryptAES(string content, string password)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(password);
byte[] data = Convert.FromBase64String(content);
byte[] iv = new byte[keyMaterial.Length];
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Decrypt(key, data, iv);
return Encoding.UTF8.GetString(cipherText, 0, cipherText.Length);
}
WinRTCrypto is available as part of PCLCrypto.

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.

C# UTF8 Encoding issue with AES Encryption

I'm creating a TCP based chat client. I'm trying to Encrypt some of the data with AES (more security) I have a AES encryption class and it uses UTF-8 by default as the out going and incoming Encoding type. But for some reason when i pass the information over the TCPClient (using UTF-8) and get it the other side it is throwing an error:
`System.Security.Cryptography.CryptographicException: Length of the data to decrypt is invalid.
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()`
So I recreated the problem without using the TCP client, just taking the AES encrypted data and putting it through a UTF-8 Encoding system that gets the string of the byte array then re-gets the byte array all using UTF-8 (basically the same thing as what happens over the network (without the string))
This method works:
string dataToEncrypt = "Hello World";
byte[] key = Encryption.AesEncryption.GenerateKey(32);
byte[] iv = Encryption.AesEncryption.GenerateKey(16);
byte[] encrypted = Encryption.AesEncryption.EncryptString(dataToEncrypt, key, iv);
string decrypted = Encryption.AesEncryption.DecryptedBytes(encrypted, key, iv);
The method doesn't work (throws the error from above)
Encoding encoding = Encoding.UTF8;
string dataToEncrypt = "Hello World";
byte[] key = Encryption.AesEncryption.GenerateKey(32);
byte[] iv = Encryption.AesEncryption.GenerateKey(16);
byte[] encrypted = Encryption.AesEncryption.EncryptString(dataToEncrypt, key, iv);
string encstring = encoding.GetString(encrypted);
byte[] utf8encrypted = encoding.GetBytes(encstring);
string decrypted = Encryption.AesEncryption.DecryptedBytes(utf8encrypted, key, iv);
What am i doing wrong?
This is my Encryption Class:
public sealed class AesEncryption
{
private byte[] Key;
public Encoding Encoder = Encoding.UTF8;
public AesEncryption(byte[] key)
{
Key = key;
}
public byte[] Encrypt(string text, byte[] iv)
{
var bytes = Encoder.GetBytes(text);
var rm = new RijndaelManaged();
var encrypter = rm.CreateEncryptor(Key, iv);
var ms = new MemoryStream();
var cs = new CryptoStream(ms, encrypter, CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
var output = ms.ToArray();
cs.Close();
ms.Close();
return output;
}
public string Decrypt(byte[] encrypted, byte[] iv)
{
var ms = new MemoryStream();
var cs = new CryptoStream(ms,
new RijndaelManaged().CreateDecryptor(Key, iv),
CryptoStreamMode.Write);
cs.Write(encrypted, 0, encrypted.Length);
cs.FlushFinalBlock();
var output = ms.ToArray();
cs.Close();
ms.Close();
return Encoder.GetString(output);
}
public static byte[] EncryptString(string text, byte[] key, byte[] iv)
{
var ec = new AesEncryption(key);
return ec.Encrypt(text, iv);
}
public static string DecryptedBytes(byte[] encrypted, byte[] key, byte[] iv)
{
var ec = new AesEncryption(key);
return ec.Decrypt(encrypted, iv);
}
public static byte[] GenerateKey(int length)
{
Random rnd = new Random();
var chars = "1!2#3#4$5%6^7&8*9(0)-_=+qQwWeErRtTyYuUiIoOpP[{]}\\|aAsSdDfFgGhHjJkKlL;:'\"zZxXcCvVbBnNmM,<.>/?".ToCharArray();
string randomizedKey = "";
for (int i = 0; i < length; i++)
{
randomizedKey += chars[rnd.Next(0, chars.Length)];
}
return randomizedKey.ToByteArray();
}
}
UTF-8 does not perfectly represent the bytes. The short and simple answer is: Transmit bytes, not a UTF-8 string. If you must have a string, encode it in Base64.

AES cbc padding encryption/decryption on cross platform (.net c# and codename one bouncy castle)

Encryption/Decryption won't work in cross platform.
I have used this link to encrypt/decrypt text using bouncy castle AES cipher within codename one.
AES Encryption/Decryption with Bouncycastle Example in J2ME
While from server side (.net) , i am using this link to implement same method.
http://zenu.wordpress.com/2011/09/21/aes-128bit-cross-platform-java-and-c-encryption-compatibility/
now i am not getting any error but encrypted from codename one will not getting fully decrypted on server side and vice a versa.
any one please help me out on this.
Code from Codename one:
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Base64;
public class Test
{
private static PaddedBufferedBlockCipher cipher = null;
public static void main(String[] args)
{
try
{
byte key[] = "MAKV2SPBNI992122".getBytes("UTF-8");
byte[] iv = new byte[16];
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new CBCBlockCipher(
new AESEngine()) );
//Encryption
String plainText = "Hello How are you !2#&*()% 123456#";
byte[] plainData = plainText.getBytes("UTF-8");
KeyParameter keyParam = new KeyParameter(key);
CipherParameters ivAndKey = new ParametersWithIV(keyParam, iv);
cipher.init(true, ivAndKey);
byte[] ciptherBytes = cipherData(plainData); //48
String cipherText = new String(Base64.encode(ciptherBytes), "UTF-8");//FileUtil.getStringFromByteArray(Base64.encode(ciptherBytes));
System.out.println("encrypted >> "+cipherText);
//Decryption
byte[] cipherData = Base64.decode(cipherText);
ivAndKey = new ParametersWithIV(keyParam, iv);
cipher.init(false, ivAndKey);
plainText = new String(cipherData(cipherData), "UTF-8");//FileUtil.getStringFromByteArray(cipherData(cipherData));
System.out.println("decrypted >> "+plainText);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static byte[] cipherData(byte[] data)
throws CryptoException
{
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return result;
}
Code from .net:
public static RijndaelManaged GetRijndaelManaged(String secretKey)
{
var keyBytes = new byte[16];
var secretKeyBytes = Encoding.UTF8.GetBytes(secretKey);
Array.Copy(secretKeyBytes, keyBytes, Math.Min(keyBytes.Length, secretKeyBytes.Length));
return new RijndaelManaged
{
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
KeySize = 128,
BlockSize = 128,
Key = keyBytes,
IV = keyBytes
};
}
public static byte[] EncryptCBC(byte[] plainBytes, RijndaelManaged rijndaelManaged)
{
return rijndaelManaged.CreateEncryptor()
.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
}
public static byte[] DecryptCBC(byte[] encryptedData, RijndaelManaged rijndaelManaged)
{
return rijndaelManaged.CreateDecryptor()
.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
}
public static String EncryptCBCStr(String plainText, String key)
{
var plainBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(EncryptCBC(plainBytes, GetRijndaelManaged(key)));
}
public static String DecryptCBCStr(String encryptedText, String key)
{
var encryptedBytes = Convert.FromBase64String(encryptedText);
return Encoding.UTF8.GetString(DecryptCBC(encryptedBytes, GetRijndaelManaged(key)));
}
// call
var PlainText = "Hello How are you !2#&*()% 123456#";
var EncryptionKey = "MAKV2SPBNI992122";
var cypherCBC = EncryptCBCStr(PlainText, EncryptionKey);
var decryptCBC = DecryptCBCStr(cypherCBC, EncryptionKey);
Thanks in adv.
This issue has been fixed...it is just key/IV bytes issue.as in .net there is same key and IV when in java i have used different IV.
correction in java code:
instead of this
byte key[] = "MAKV2SPBNI992122".getBytes("UTF-8");
byte[] iv = new byte[16];
use this.
byte key[] = "MAKV2SPBNI992122".getBytes("UTF-8");
byte[] iv = "MAKV2SPBNI992122".getBytes("UTF-8");

Categories

Resources