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.