Java-decrypted file ruined - java

I have a program that has to encrypt an audio file and then decrypt it if needed. I tested my program on some other types of files, like .bin or .txt. The problem I get is that the decrypted file has some weird characters before the actual content, like the source file contains "010101" and after encryption-decryption it has "’w0w 010101".
My encryption method code goes here:
public void cipherTheAudioFile(String fileDir, String fileToCipher) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException {
File audioSourceFile = new File(fileDir + "\\" + fileToCipher);
ObjectOutputStream oos = new ObjectOutputStream(
new CipherOutputStream(new FileOutputStream(
new java.io.File("").getAbsolutePath().toString() + "/encrypted/" + fileToCipher + ".sky"), cipher));
byte[] audioFileInBytes = FileUtils.readFileToByteArray(audioSourceFile);
oos.write(audioFileInBytes);
fos = new FileOutputStream(KEY_FILE);
SecretKeyFactory skf = SecretKeyFactory.getInstance(ENCRYPTION_ALGORITHM);
DESKeySpec keyspec = (DESKeySpec) skf.getKeySpec(key, DESKeySpec.class);
fos.write(keyspec.getKey());
fos.close();
oos.close();
}
My decryption method code goes here:
public void decryptTheAudioFile(String fileDir, String fileToDecipher) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, ClassNotFoundException, InvalidKeySpecException, InvalidKeyException {
fis = new FileInputStream(keyFile);
byte[] keyspecbytes = new byte[fis.available()];
File fileToWriteIn = createFileToWriteIn(fileDir, fileToDecipher);
fis.read(keyspecbytes);
SecretKeyFactory skf = SecretKeyFactory.getInstance(encryptionAlgorithm);
DESKeySpec keyspec = new DESKeySpec(keyspecbytes);
SecretKey key = skf.generateSecret(keyspec);
Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
cipher.init(Cipher.DECRYPT_MODE, key);
ObjectInputStream ois = new ObjectInputStream(
new CipherInputStream(
new FileInputStream(new java.io.File("").getAbsolutePath().toString() + "/encrypted/" + fileToDecipher + ".sky"), cipher));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileToWriteIn));
byte[] audioFileInBytes = new byte[1024];
int numRead = 0;
while ((numRead = ois.read(audioFileInBytes)) >= 0) {
oos.write(audioFileInBytes, 0, numRead);
}
oos.close();
fis.close();
ois.close();
}
P.S. It could be something with the encoding, but I am not really sure.
EDITED
Ok, I have changed to the FileWriters, but still no change. Here goes the code:
OutputStream os = new FileOutputStream(new java.io.File("").getAbsolutePath().toString() + "/encrypted/" + fileToCipher + ".sky");
CipherInputStream cis = new CipherInputStream(new FileInputStream(audioSourceFile), cipher);
byte[] audioFileInBytes = new byte[1024];
int numRead = 0;
while ((numRead = cis.read(audioFileInBytes)) >= 0) {
os.write(audioFileInBytes, 0, numRead);
}
Likewise goes the decryptor.

The problem is in the way that the decryptTheAudioFile method writes the file. Specifically, the problem is that it is using an ObjectOutputStream. That is adding an object serialization header. But it doesn't belong there at all.
The solution is to get rid of this from decryptTheAudioFile:
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(fileToWriteIn));
and replace it with this:
OutputStream os = new FileOutputStream(fileToWriteIn);
and change the rest of the code to write to os. Your code needs to mirror how you are reading the file in cipherTheAudioFile.
It would be a good idea to get rid of the other ObjectStream instances too and simply read and write to plain Streams. The other ObjectStreams are harmless (mostly), but they don't actually achieve anything.

Drop all the ObjectOutputStreams and ObjectInputStreams. You are writing a byte array so they are unnecessary. The extra bytes you see are probably telling you the type and size of the byte[].

Related

How to encrypt Credentials object - Cipher.doFinal, SealedObject, or CipherOutputStream?

I need to encrypt a set of user credentials and send it to a SOAP web service. The following code snippet (I think it's C#) is provided in the documentation, and my Java code is based on it.
private string Encrypt256(string text, AesCryptoServiceProvider aes)
{
// Convert string to byte array
byte[] src = Encoding.Unicode.GetBytes(text);
// encryption
using (ICryptoTransform encrypt = aes.CreateEncryptor())
{
byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
// Convert byte array to Base64 strings
return Convert.ToBase64String(dest);
}
}
...
Credentials credential = new Credentials();
credential.UserName = "username";
credential.Password = "password";
credential.ClientUtcTime = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture);
//--Serialize credential
XmlSerializer serializer = new XmlSerializer(credential.GetType());
string xmlCredential = string.Empty;
using (var stringwriter = new System.IO.StringWriter())
{
serializer.Serialize(stringwriter, credential);
xmlCredential = stringwriter.ToString();
}
//--Encrypt credential with AES256 symmetric
String encryptedCredential = Encrypt256(xmlCredential, aesServiceProvider);
...
The following is my Java code.
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256);
SecretKey sk = kg.generateKey();
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, sk);
Credentials cred = new UsernamePasswordCredentials("username", "password");//no need for time field?
String eCred = Base64.encodeBase64String(aesCipher.doFinal(objectToByteArray(cred)));
...
private byte[] objectToByteArray(Object obj) {
byte[] bytes = null;
try (
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
) {
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
}
catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
Then I came across SealedObject and CipherOutputStream. I tried writing code snippets for those.
Using SealedObject
// slight change here; cred must implement Serializable
UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username", "password");
// same as above except for the following two lines
SealedObject so = new SealedObject(cred, aesCipher);
String eCred = Base64.encodeBase64String(objectToByteArray(so));
Using CipherOutputStream
Credentials cred = new UsernamePasswordCredentials("username", "password");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
CipherOutputStream cos = new CipherOutputStream(bos, aesCipher);
cos.write(objectToByteArray(cred));
cos.close();
String eCred = Base64.encodeBase64String(bos.toByteArray());
For all three code snippets, is the code correct? Considering that this code will be called frequently, which approach is the most efficient?

Android decryption: Error while finalizing cipher

I am using Android to encrypt and encrypt images sent between apps.
The encryption works well but when the file arrives at the destination it will not decrypt. Now I have copied the file at the destination app and decrypted it successfully using 3rd-party software.
The error I get is:"Error while finalizing cipher" at CipherInputStream (CipherInputStream.java:107) caused by IllegalBlockSizeException.
The encryption & decryption code is below:
public static String encrypt(String plainFile, String encryptedFile) throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
// Here you read the cleartext.
File extStore = Environment.getExternalStorageDirectory();
FileInputStream fis = new FileInputStream(plainFile);
// This stream write the encrypted text. This stream will be wrapped by
// another stream.
FileOutputStream fos = new FileOutputStream(encryptedFile);
// Length is 16 byte
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
// Create cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
// Wrap the output stream
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
// Write bytes
int b;
byte[] d = new byte[8];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
fis.close();
return encryptedFile;
}
static String decrypt(String plainFile, String encryptedFile) throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
File encFile=new File(encryptedFile);
FileInputStream fis = new FileInputStream(encFile);
FileOutputStream fos = new FileOutputStream(plainFile);
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
return plainFile;
}
Any ideas? Thanks!
Ronan
Update:
The received encrypted file is consistently 1 byte smaller that the original file which seems to be generating the error. The error re block size is triggered at the code line
while ((b = fis.read(d)) != -1) { in the decrypt function.
Update:
Thanks for the feedback. The ultimate solution is as defined at last block incomplete with CipherInputStream/CipherOutputStream, even with padding AES/CBC/PKCS5Padding
Ronan

Cannot decrypt the encrypted file?

I tried to encrypt my file by this way:
Encrypt:
static void encrypt(String strInput , String strOutput) throws IOException,
NoSuchAlgorithmException,NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream(strInput);
FileOutputStream fos = new FileOutputStream(strOutput);
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
int b;
byte[] d = new byte[8];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
fis.close();
}
and decrypt it back by:
Decrypt:
static String decrypt(String strInput) throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream(strInput);
int endFile = strInput.length() - 4;
String strOut = strInput.substring(0, endFile) + "xx.jpg";
FileOutputStream fos = new FileOutputStream(strOut);
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
return strOut;
}
However, the result file's size is 0 kb and when I tried to troubleshoot b = cis.read(d) in decrypt, always returns -1, also cis.available() always returns 0. Can anyone advise me which part of my code is wrong?
Note: I can ensure that the file that is going to be decrypted is always exist.
I believe that this problem is because you are trying to decrypt data that is not encrypted (or not properly encrypted).
In your decrypt() method, the CipherOutputStream hides all exception that the Cipher class may be throwing. See javadoc for CipherOutputStream:
Moreover, this class catches all exceptions that are not thrown by its ancestor classes.
To expose the problem, you may want to implement the cipher usage manually. Here is a quick example:
static String decrypt(String strInput) throws IOException,
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
FileInputStream fis = new FileInputStream(strInput);
int endFile = strInput.length() - 4;
String strOut = strInput.substring(0, endFile) + "xx.txt";
FileOutputStream fos = new FileOutputStream(strOut);
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
int b;
byte[] d = new byte[8];
while ((b = fis.read(d)) != -1) {
fos.write(cipher.update(d));
}
fos.write(cipher.doFinal());
fos.flush();
fos.close();
fis.close();
return strOut;
}
The algorithm you posted in your question seems to work fine for valid inputs. For example, let`s assume the following main:
public static void main(String[] argv) {
try {
encrypt("test.txt", "XXX.txt");
decrypt("XXX.txt");
}
catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
Using this, and testing both with a text file and a JPG file, your algorithms executed flawlessly. However, when using an invalid input to the decryption algorithm, then the problem you described started to appear.
For testing, lets imagine that we make the "mistake" of trying to decrypt the file that was in clear like so (just changing the parameter passed to decrypt() in the main):
encrypt("test.txt", "XXX.txt");
decrypt("test.txt");
Then of course the padding on the input to the decrypt() method will be wrong and we should get an exception.
Using your version of decrypt()however, there is no exception. All we get is an empty file.
Using the modified version fo the decrypt() method that is shown above we get the following exception:
javax.crypto.BadPaddingException: Given final block not properly padded
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:313)
at javax.crypto.Cipher.doFinal(Cipher.java:1970)
at MainTest.decrypt(MainTest.java:71)
at MainTest.main(MainTest.java:21)

getting javax.crypto.IllegalBlockSizeException error when decrypting

I'm trying to encrypt/decrypt text from a file but i am receiving the following error:
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
I'm using AES 128 bit with AES/ECB/PKCS5Padding. Any idea why I am getting this error?
Here is my code:
public class AES_Encryption {
public static void main(String[] args) throws Exception {
String str = new Scanner(new File("src//plainText.txt")).useDelimiter("\\Z").next();
FileWriter fstream = new FileWriter("src//cipherText.txt");
BufferedWriter out = new BufferedWriter(fstream);
FileWriter fstream2 = new FileWriter("src//decrpytedText.txt");
BufferedWriter out2 = new BufferedWriter(fstream2);
System.out.println("" + str);
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
Key key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = cipher.doFinal(str.getBytes());
String ct = new String(cipherText);
System.out.println( new String(cipherText, "UTF8") );
out.append(ct);
out.close();
String cipherT = new Scanner(new File("src//cipherText.txt")).useDelimiter("\\Z").next();
cipher.init(Cipher.DECRYPT_MODE, key);
//byte[] decVal = Base64.decode(cipherT.getBytes());
byte[] newPlainText = cipher.doFinal(cipherT.getBytes());
String dt = new String(newPlainText, "UTF8");
out2.append(dt);
out2.close();
}
}
Your error is treating the ciphertext as a string:
String ct = new String(cipherText); // <--- Noooo!
There will be values in your byte array that cannot be expressed as characters in the default charset.
Always treat your ciphertext as a byte array, even when reading or writing to files.
One get the IllegalBlockSizeException in following case as mentioned in Cipher API documentaion:
IllegalBlockSizeException - If this cipher is a block cipher, no padding has been requested (only in encryption mode), and the total input length of the data
processed by this cipher is not a multiple of block size
In Your case you are Encrypting the String correctly , But while decryption you are treating the cipherText as String and then
you are putting cipherT.getBytes() byte array in doFinal method of Cipher. The byte array conversion of String is not same as reading byte array from the file in binary mode.
The functionality and limitation of String.toBytes() as mentioned in String API documentaion is as follows:
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. The
behavior of this method when this string cannot be encoded in the
default charset is unspecified. The CharsetEncoder class should be
used when more control over the encoding process is required.
What I suggest for you is to read the cipherText.txt File in binary mode and then put the byte array you got after reading the file in doFinal method of Cipher . I have modified your code in following way:
public class AES_Encryption {
public static void main(String[] args) throws Exception {
String str = new Scanner(new File("plainText.txt")).useDelimiter("\\t").next();
FileOutputStream fstream = new FileOutputStream("cipherText.txt");
BufferedOutputStream out = new BufferedOutputStream(fstream);
FileOutputStream fstream2 = new FileOutputStream("decrpytedText.txt");
BufferedOutputStream out2 = new BufferedOutputStream(fstream2);
System.out.println("INPUT String:\n" + str);
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
Key key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = cipher.doFinal(str.getBytes());
System.out.println("ENCRYPTED String:\n"+new String(cipherText, "UTF8") );
out.write(cipherText);
out.flush();
out.close();
//String cipherT = new Scanner(new File("cipherText.txt")).nextLine();
BufferedInputStream bfin = new BufferedInputStream(new FileInputStream(new File("cipherText.txt")));//To read the file in Binary Mode.
cipher.init(Cipher.DECRYPT_MODE, key);
int BUFFERSIZE = 1024;
byte[] readBytes = new byte[BUFFERSIZE];
byte[] data = null;
int totalRead = -1;
while( (totalRead = bfin.read(readBytes))!=-1)
{
byte[] temp = new byte[(data == null ? totalRead : data.length)];
System.arraycopy((data==null ? readBytes : data),0,temp,0, temp.length);
data = new byte[(data == null ? 0 : data.length) + totalRead];
System.arraycopy(temp, 0, data, 0, temp.length);
System.arraycopy(readBytes, 0, data, data.length - temp.length, totalRead);
}
if (data!=null)
{
byte[] newPlainText = cipher.doFinal(data);
out2.write(newPlainText);
out2.flush();
System.out.println("DECRYPTED String:\n"+new String(newPlainText,"UTF8"));
}
else
{
System.out.println("No Data Found");
}
//String dt = new String(newPlainText, "UTF8");
out2.close();
}
}
I hope this would help you in resolving the exception you getting ...

Java - Missing final characters when encrypting using blowfish

I am using some java code that encrypts the contents of a text file using Blowfish. When I convert the encrypted file back (i.e. decrypt it) the string is missing a character from the end. Any ideas why? I am very new to Java and have been fiddling with this for hours with no luck.
The file war_and_peace.txt just contains the string "This is some text". decrypted.txt contains "This is some tex" (with no t on the end). Here is the java code:
public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}
public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
}
private static byte[] getBytes(String toGet)
{
try
{
byte[] retVal = new byte[toGet.length()];
for (int i = 0; i < toGet.length(); i++)
{
char anychar = toGet.charAt(i);
retVal[i] = (byte)anychar;
}
return retVal;
}catch(Exception e)
{
String errorMsg = "ERROR: getBytes :" + e;
return null;
}
}
public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
String iv = "12345678";
byte[] IVBytes = getBytes(iv);
IvParameterSpec IV = new IvParameterSpec(IVBytes);
byte[] KeyData = key.getBytes();
SecretKeySpec blowKey = new SecretKeySpec(KeyData, "Blowfish");
//Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
Cipher cipher = Cipher.getInstance("Blowfish/CBC/NoPadding");
if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, blowKey, IV);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, blowKey, IV);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}
public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[4096];
//byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}
public static void main(String[] args) {
//Encrypt the reports
try {
String key = "squirrel123";
FileInputStream fis = new FileInputStream("war_and_peace.txt");
FileOutputStream fos = new FileOutputStream("encrypted.txt");
encrypt(key, fis, fos);
FileInputStream fis2 = new FileInputStream("encrypted.txt");
FileOutputStream fos2 = new FileOutputStream("decrypted.txt");
decrypt(key, fis2, fos2);
} catch (Throwable e) {
e.printStackTrace();
}
}
`
There is a couple of things not optimal here.
But let's first solve your problem. The reason why the last portion of your input is somehow missing is the padding you specify: none! Without specifying a padding, the Cipher can just operate on full-length blocks (8 bytes for Blowfish). Excess input that is less than a block long will be silently discarded, and there's your missing text. In detail: "This is some text" is 17 bytes long, so two full blocks will be decrypted, and the final 17th byte, "t", will be discarded.
Always use a padding in combination with symmetric block ciphers, PKCS5Padding is fine.
Next, when operating with Cipher, you don't need to implement your own getBytes() - there's String#getBytes already doing the job for you. Just be sure to operate on the same character encoding when getting the bytes and when reconstructing a String from bytes later on, it's a common source of errors.
You should have a look at the JCE docs, they will help you avoiding some of the common mistakes.
For example, using String keys directly is a no-go for symmetric cryptography, they do not contain enough entropy, which would make it easier to brute-force such a key. The JCE gives you theKeyGenerator class and you should always use it unless you know exactly what you are doing. It generates a securely random key of the appropriate size for you, but in addition, and that is something people tend to forget, it will also ensure that it doesn't create a weak key. For example, there are known weak keys for Blowfish that should be avoided in practical use.
Finally, you shouldn't use a deterministic IV when doing CBC encryption. There are some recent attacks that make it possible to exploit this, resulting in total recovery of the message, and that's obviously not cool. The IV should always be chosen at random (using a SecureRandom) in order to make it unpredictable. Cipher does this for you by default, you can simply obtain the used IV after encryption with Cipher#getIV.
On another note, less security-relevant: you should close streams in a finally block to ensure they're closed at all cost - otherwise you will be left with an open file handle in case of an exception.
Here's an updated version of your code that takes all these aspects into account (had to use Strings instead of files in main, but you can simply replace it with what you had there):
private static final String ALGORITHM = "Blowfish/CBC/PKCS5Padding";
/* now returns the IV that was used */
private static byte[] encrypt(SecretKey key,
InputStream is,
OutputStream os) {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
return cipher.getIV();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private static void decrypt(SecretKey key,
byte[] iv,
InputStream is,
OutputStream os)
{
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private static void doCopy(InputStream is, OutputStream os)
throws IOException {
try {
byte[] bytes = new byte[4096];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
} finally {
is.close();
os.close();
}
}
public static void main(String[] args) {
try {
String plain = "I am very secret. Help!";
KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish");
SecretKey key = keyGen.generateKey();
byte[] iv;
InputStream in = new ByteArrayInputStream(plain.getBytes("UTF-8"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
iv = encrypt(key, in, out);
in = new ByteArrayInputStream(out.toByteArray());
out = new ByteArrayOutputStream();
decrypt(key, iv, in, out);
String result = new String(out.toByteArray(), "UTF-8");
System.out.println(result);
System.out.println(plain.equals(result)); // => true
} catch (Exception e) {
e.printStackTrace();
}
}
You have your CipherInputStream and CipherOutputStream mixed up. To encrypt, you read from a plain inputstream and write to a CipherOutputStream. To decrypt ... you get the idea.
EDIT:
What is happening is that you have specified NOPADDING and you are attempting to encrypt using a CipherInputStream. The first 16 bytes form two valid complete blocks and so are encrypted correctly. Then there is only 1 byte left over, and when the CipherInputStream class receives the end-of-file indication it performs a Cipher.doFinal() on the cipher object and receives an IllegalBlockSizeException. This exception is swallowed, and read returns -1 indicating end-of-file. If however you use PKCS5PADDING everything should work.
EDIT 2:
emboss is correct in that the real issue is simply that it is tricky and error-prone to use the CipherStream classes with the NOPADDING option. In fact, these classes explicitly state that they silently swallow every Security exception thrown by the underlying Cipher instance, so they are perhaps not a good choice for beginners.
Keys are binary, and String is not a container for binary data. Use a byte[].
When I had this problem I had to call doFinal on the cipher:
http://docs.oracle.com/javase/1.4.2/docs/api/javax/crypto/Cipher.html#doFinal()

Categories