I'm trying to encryt/decrypt using RSAEngine library at bouncy castle, with a 2048 bit length key. I'm able to create the keys, store in different files and get from the files, but when I decrypt an image it makes something that I don't know that the file decrypted is not shown correctly.Files are created correctly,and I think the problem is at processBlock method while encrypting and/or decrypting.The code is the following to encrypt:
InputStream clearTextFile;
FileOutputStream textFileProcessed=new FileOutputStream(fileName);
//getKey is a method I implemented and works correctly
RSAKeyParameters key=getKey(keyFileName);
RSAEngine rsaEngine=new RSAEngine();
rsaEngine.init(true,key);
clearTextFile=new FileInputStream(nameClearTextFile);
byte[] bytesReaded;
int nBytesReaded;
int inputBlockSize=rsaEngine.getInputBlockSize();
do
{
bytesReaded = new byte[inputBlockSize];
nBytesReaded=clearTextFile.read(bytesReaded);
if(nBytesReaded>-1)
{ //This is for the last block if it's not 256 byte length
if(nBytesReaded<inputBlockSize)
{
byte[] temp=new byte[nBytesReaded];
for(int i=0;i<nBytesReaded;i++)
{
temp[i]=bytesReaded[i];
}
byte[] encryptedText=rsaEngine.processBlock(temp,0,nBytesReaded);
textFileProcessed.write(encryptedText);
}
else
{
byte[] encryptedText=rsaEngine.processBlock(bytesReaded,0,inputBlockSize);
textFileProcessed.write(encryptedText);
}
}
}while(nBytesReaded>-1);
textFileProcessed.flush();
textFileProcessed.close();
textFileProcessed.close();
And to decrypt:
InputStream encryptedTextFile=new FileInputStream(nameOfFile);
OutputStream decryptedTextFile=new FileOutputStream(nameOfFile);
RSAKeyParameters key=getKey(nameKeyFile);
RSAEngine rsaEngine=new RSAEngine();
rsaEngine.init(false,key);
byte[] bytesReaded;
int nBytesReaded;
int inputBlockSize=rsaEngine.getInputBlockSize();
do
{
bytesLeidos = new byte[inputBlockSize];
nBytesReaded=encryptedTextFile.read(bytesReaded);
if(nBytesReaded>-1)
{
byte[] decryptedText=rsaEngine.processBlock(bytesReaded,0,inputBlockSize);
decryptedTextFile.write(decryptedText);
}
}while(nBytesReaded>-1);
decryptedTextFile.flush();
decryptedTextFile.close();
encryptedTextFile.close();
Thanks in advance
RSAEngine does not add padding, you will lose any leading zeros in your data blocks as a result. You need to use one of the encoding modes available as well.
I'd recommend using a symmetric key algorithm as well and just using RSA to encrypt the symmetric key. It will be a lot faster, and depending on your data, safer as well.
Regards,
David
I think you need to change this line:
if(nBytesReaded>1)
to this
if(nBytesReaded>-1)
And change this in the decypt part, maybe:
rsaEngine.init(false,clave);
to this
rsaEngine.init(false,key);
But there may be more. You aren't encrypting the whole input if the last block isn't full size.
Related
I'm writing a program to encrypt and decrypt data.
for encrypting,
I created a symmetric key using keyGenerator.
I transferred the key to the cipher, and created a string version of the key:
String keyString = Base64.getEncoder().encodeToString(symmetricKey.getEncoded());
in order to store it in a configuration file (so I can retrieve the key in the decrypt function).
Now, in the decrypt function I need to get that string back to key format, so I can send it as a parameter to the cipher in dercypt mode.
I convert it back to key this way:
byte[] keyBytes = key.getBytes(Charset.forName("UTF-8"));
Key newkey = new SecretKeySpec(keyBytes,0,keyBytes.length, "AES");
And I transffer it to the cipher and write the output (the decrypted data) using CipherInputStream:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newkey, newiv, SecureRandom.getInstance("SHA1PRNG"));
CipherInputStream cipherInputStream = new CipherInputStream(
new ByteArrayInputStream(encryptedBytes), cipher);
ArrayList<Byte> decryptedVal = new ArrayList<>();
int nextByte;
while ((nextByte = cipherInputStream.read()) != -1) {
decryptedVal.add((byte) nextByte);
}
byte[] bytes = new byte[decryptedVal.size()];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = decryptedVal.get(i);
}
String decryptedData = new String(bytes);
cipherInputStream.close();
System.out.println("decryptedData: " + decryptedData);
I get this error:
Exception in thread "main" java.io.IOException: javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
So I suspect that there might be a problem with the way I treat the key.
Any suggestions? help would be appreciated!
I think you have not sent IV to decryption function. For decryption in CBC mode, you must provide an IV which is used in encryption process.
Update:
IV will affect only first block in CBC decryption mode. So my answer may affect the unpadding if your data is less than 1 block. It will just change the decrypted plaintext of the first block otherwise.
Of course you get this error: first you apply base 64 encoding:
String keyString = Base64.getEncoder().encodeToString(symmetricKey.getEncoded());
and then you use character-encoding to turn it back into bytes:
byte[] keyBytes = key.getBytes(Charset.forName("UTF-8"));
which just keeps be base64 encoding, probably expanding the key size from 16 bytes to 24 bytes which corresponds with a 192 bit key instead of a 128 bit key. Or 24 bytes key to a 32 bytes key of course - both seem to work.
To solve this you need to use Base64.getDecoder() and decode the key.
Currently you get a key with a different size and value. That means that each block of plaintext, including the last one containing the padding, will decrypt to random plaintext. As random plaintext is unlikely to contain valid padding, you will be greeted with a BadPaddingException.
Reminder:
encoding, e.g. base 64 or hex: encoding bytes to a text string
character-encoding, e.g. UTF-8 or ASCII: encoding a text string into bytes
They are not opposites, that would be decoding and character-decoding respectively.
Remarks:
yes, listen to Ashfin; you need to use a random IV during encryption and then use it during decryption, for instance by prefixing it to the ciphertext (unencrypted);
don't use ArrayList<Byte>; that stores a reference to each separate byte (!) - use ByteArrayOutputStream or any other OutputStream instead;
you can better use a byte buffer and use that to read / write to the streams (note that the read function may not fill the buffer, even if at the start or in the middle of the stream) - reading a single byte at the time is not performant;
lookup try-with-resources for Java;
using a KeyStore may be better than storing in a config file;
GCM mode (AES/GCM/NoPadding) also authenticates data and should be preferred over CBC mode.
I'm using AES Decryption on my Android Project to decrypt large string objects ( > 1 MB ).
I'm using this method :
public static String decryptAES(String cryptedString, byte[] byteArrayAESKey) {
try {
IvParameterSpec ips = new IvParameterSpec(General.InitVector.getBytes("UTF-8"));
SecretKey aesKey = new SecretKeySpec(byteArrayAESKey, "AES");
byte[] TBCrypt = Base64.decode(cryptedString, Base64.DEFAULT);
// Decryption cipher
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
// Initialize PBE Cipher with key and parameters
decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ips);
// Decrypt the cleartext
byte[] deciphertext = decryptCipher.doFinal(TBCrypt); // this may take a long time depending on string input length
return new String(deciphertext, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
Log.e("AES", "Decrypt failed : " + e.getMessage());
return "";
}
}
It works well, but on large encrypted strings, it takes a long time on many devices.
Is there a way to improve this method on android devices ? Should I cut the encrypted string to accelerate the process ? Should I use SpongyCastle ?
byte[] deciphertext = decryptCipher.doFinal(TBCrypt); Dont do that! Instead consider using streams, maybe directly to output file stream (if needed)?.
Is there a way to improve this method on android devices ?
Maybe, you could take a look here , and there's saying that the AES is pretty fast, though.
Should I cut the encrypted string to accelerate the process ?
Yes, this should be the problem. Usually you only have to encrypt the critical parts of the data. Maybe a refactor should resolve the question.
Should I use SpongyCastle ?
Don't know, but if i where you i would first look at the data encrypted.
I have written code in vb.net to encrypt a file from a memory stream. I also decrypt the file as well as copy the memory stream to a file to assure encryption/ decryption works. My vb solution works.
However my need is to decrypt using Java. When I decrypt my file, I always get an extra "?" character at the very beginning of the file, but other than that the resullts are perfect. Has anyone seen anything like this before? I must admit, my results are from using only one set of data, but I've encrypted it twice using new keys and vectors both times.
A few details. I'm using AES, PKCS7 padding in vb, and PKCS5 padding in Java. The file can be of arbitrary length. Any help is appreciated.
I am posting this from my phone, and don't have the code handy. I can add it tomorrow. I'm just hoping that this description rings a bell with someone.
Thanks,
SH
When I wrote to the MemoryStream in VB, I declared a StreamWriter like so:
Writer = New IO.StreamWriter(MS, System.Text.Encoding.UTF8)
Here's my VB.NET encryption function.
Public Shared Function WriteEncryptedFile(ms As MemoryStream, FileName As String) As List(Of Byte())
Try
Dim original() As Byte
Dim myAes As System.Security.Cryptography.Aes = Aes.Create()
myAes.KeySize = 128
myAes.Padding = PadMode
Dim keys As New List(Of Byte())
keys.Add(myAes.Key)
keys.Add(myAes.IV)
original = ms.ToArray
Dim encryptor As ICryptoTransform = myAes.CreateEncryptor(myAes.Key, myAes.IV)
Using FileEncrypt As New FileStream(FileName, FileMode.Create, FileAccess.Write)
Using csEncrypt As New CryptoStream(FileEncrypt, encryptor, CryptoStreamMode.Write)
csEncrypt.Write(original, 0, original.Length)
csEncrypt.FlushFinalBlock()
FileEncrypt.Flush()
FileEncrypt.Close()
csEncrypt.Close()
End Using
End Using
Return keys
Catch e As Exception
MsgBox("Error during encryption." & vbCrLf & e.Message)
End Try
Return Nothing
End Function
And here's the Java decryption:
public static void DecryptLIGGGHTSInputFile(String fileIn, String fileOut, String base64Key, String base64IV) throws Exception
{
// Get the keys from base64 text
byte[] key = Base64.decodeBase64(base64Key);
byte[] iv= Base64.decodeBase64(base64IV);
// Read fileIn into a byte[]
int len = (int)(new File(fileIn).length());
byte[] cipherText = new byte[len];
FileInputStream bs = new FileInputStream(fileIn);
bs.read(cipherText, 1, len-1);
System.out.println(cipherText.length);
System.out.println((double)cipherText.length/128);
bs.close();
// Create an Aes object
// with the specified key and IV.
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// Encrypt the message.
SecretKey secret = new SecretKeySpec(key, "AES");
/*
cipher.init(Cipher.ENCRYPT_MODE, secret, ivspec);
cipherText = cipher.doFinal("Hello, World!".getBytes("UTF-8"));
System.out.println(cipherText);
*/
cipher.init(Cipher.DECRYPT_MODE, secret , new IvParameterSpec(iv));
String plaintext = new String(cipher.doFinal(cipherText), "UTF-8");
System.out.println(plaintext.length());
FileWriter fw = new FileWriter(fileOut);
fw.write(plaintext);
fw.close();
}
It was a BOM problem. When I created the MemoryStream with VB, I initialized it in UTF-8 encoding. The very first character in my file boosted the size and position of the stream from 0 bytes to 4 bytes, when it should have only been one. The solution was to create an encoding based on UTF-8 without Byte Order Marks, like so:
Dim UTF8EncodingWOBOM As New System.Text.UTF8Encoding(False) 'indicates to omit BOM
Writer = New IO.StreamWriter(MS, UTF8EncodingWOBOM)
I read here that there are frequently issues with encoding incompatibilities between platforms due to the presence or lack of byte order mark, as it is neither recommended or required. It's not right to use one, it's not wrong to use one. You basically have to find a way to deal with them. A plethora of other articles and postings suggested different ways to do it. The gist was, either identify them and deal with them if they exist. Since I have control of both the writing and the reading, it makes about as much sense to do away with them entirely.
SH
Preface: This is a homework assignment, and I am almost done with it -- it's just this tiny piece that is preventing me from finishing. With this information, please do not write any code for me, but possibly note what I might be doing wrong.
Okay, here is the simple idea.
Use RSA to encrypt/decrypt a file with ECB Mode. This means if there was a block size of 4, and the string was 'testdata', 'test' would be encrypted with the key, written to file, and then 'data' would be encrypted with the key and written to the file.
My implementation is using 128 as the block size, but I'm having a strange error.
Here is my code to encrypt a block of 128 and append to a file:
ArrayList<byte[]> bytes = new ArrayList<byte[]>();
String file = read_file(input_file);
int index = 0;
while (index<file.length()) {
byte[] block = file.substring(index, Math.min(index+128,file.length())).getBytes();
cipher = new BigInteger(block).modPow(public_exponent, public_modulus).toByteArray();
bytes.add(cipher);
append_bytes(output_file, cipher);
index+=128;
}
Encryption works perfectly. Here's why I think that encryption is not the issue:
Decrypting the data that is being written to the file works
Adding all encrypted data to a list contains the same data as reading the file
If decrypting from the list that I mentioned above, decryption works flawlessly.
It's the strangest issue, though.
This produces the right output:
for(int i = 0; i < bytes.size(); i++) {
decrypted = new BigInteger(bytes.get(i)).modPow(d, modulus).toByteArray();
System.out.print(new String(decrypted));
}
But that is useless, because what's the point of being able to decrypt only after encrypting.
This does not work every time, but it does work occassionaly:
index = 0;
file = new String(read_bytes(output_file));
while(index < file.length()) {
byte[] block = file.substring(index, Math.min(index+128,file.length())).getBytes();
decrypted = new BigInteger(block).modPow(d, modulus).toByteArray();
System.out.println(new String(decrypted));
index+= 128;
}
I am reading the file the same way that it was wrote to; in blocks of 128. But it does not read it properly, and because of that, decryption fails!
Any idea why this might be happening?
You are reading the cipher-text (which is binary data) into a String, then possible running into some charset convertion that messes up everything.
The decryption should read raw bytes. If you need each blocks in a different array, you may use Arrays.copyOfRange(original,from,to).
Another approach would be base64-encoding the ciphertext before writing it to the file, then base-64 decoding before decryption.
I am trying to encrypt and decrypt a message as mentioned in the below code. Basically I want to encrypt a message with a public key and convert that encrypted message from byte array to String. And decrypt this string into original text. Here are the both methods. Here encryption works fine but decryption fails (error is "Data must start with zero"). I think this is causing because I convert encrypted byte array into String.
How do I solve this? (I want to have encrypted byte array as string and use it for decryption) Is there any other approach (with public and private keys)
public static String getEncryptedMessage(String publicKeyFilePath,
String plainMessage) {
byte[] encryptedBytes;
try {
Cipher cipher = Cipher.getInstance("RSA");
byte[] publicKeyContentsAsByteArray = getBytesFromFile(publicKeyFilePath);
PublicKey publicKey = getPublicKey(publicKeyContentsAsByteArray);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plainMessage.getBytes());
return new String(encryptedBytes);
} catch (Throwable t) {
}
}
public static String getDecryptedMessage(
String privateKeyFilePath, String encryptedMessage)
{
byte[] decryptedMessage;
try {
Cipher cipher = Cipher.getInstance("RSA");
byte[] privateKeyContentsAsByteArray = getBytesFromFile(privateKeyFilePath);
PrivateKey privateKey = getPrivateKey(privateKeyContentsAsByteArray);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
decryptedMessage = cipher.doFinal(encryptedMessage.getBytes());
return new String(decryptedMessage);
} catch (Throwable t) {
}
If you look at this page (http://www.wikijava.org/wiki/Secret_Key_Cryptography_Tutorial) you will need to do base-64 encoding to turn the bytes into a string, then to decrypt it you would just decode it then decrypt.
Base-64 encoding uses the first 7 bits of a byte, to make something that is printable or emailable, for example.
UPDATE:
I made a mistake, there are 64 characters that it would be encoded in, again, in order to make it easier to use as something printable.
Why don't you treat the message as byte array from encryption to decryption? Why changing it to String in the middle? (I know it seems like a question, but it's actually an answer...)
Using RSA directly on unformatted data may leave your application vulnerable to an adaptive chosen ciphertext attack. For details please see Chapter 8, pages 288-289, of the Handbook of Applied Cryptography, a freely-available book from CRC Press. (It's well worth buying the bound edition, if you're really interested in cryptography -- you'll be stunned at the quality for the price.)
Because of this attack, most protocols that integrate RSA use RSA for encrypting randomly-generated session keys or signing hash functions with outputs that ought to be indistinguishable from random, OR using very carefully formatted messages that will fail to be correctly interpreted. (See Note 8.63 in HAC for details.)