I am working on a Encryption/Decryption program in Java. I am using a key called "secret1234" to encrypt and decrypt a message from a text file. This program uses a string for the key. However, I am interested in using a number (integer) for the key so I can generate random numbers. So, how can this program be modified to allow the key to be an integer and not a string for encrypting and descrypting the message?
This is the program:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class Program {
public static void main(String[] args) {
try {
String key = "secret1234";// This is the key
FileInputStream fis = new FileInputStream("text.txt");//text.txt is a text file with a short message
FileOutputStream fos = new FileOutputStream("encryptedText.txt");
encrypt(key, fis, fos);
FileInputStream fis2 = new FileInputStream("encryptedText.txt");
FileOutputStream fos2 = new FileOutputStream("decryptedText.txt");
decrypt(key, fis2, fos2);
} catch (Throwable e) {
e.printStackTrace();
}
}
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);
}
public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, desKey);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}
public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}
}
Use this in your code to generate the key:
String key = String.valueOf(SecureRandom.getInstance("SHA1PRNG").nextInt());
Related
Every time I run the code it says that the deciphered text file can't be found. It works without the code I can't modify (because my teacher wrote that we can't) but with it, it refuses to work. My teacher won't help me and no one else in my class knows how to code with the cipher class. I have used the PrintWriter class, and pretty much everything else. So I don't know what to do. Someone please help me figure out how to make it work.
package Crypto;
import java.util.Scanner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.FileWriter;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class Crypto {
public static void main(String[] args) throws IOException {
try {
String key = "B1LLYB0B";
FileInputStream One = new FileInputStream("CryptoPlaintext.txt");
FileOutputStream Two = new FileOutputStream("CryptoCiphertext.txt");
encrypt(key, One, Two);
Two.flush();
Two.close();
FileInputStream One2 = new FileInputStream("CryptoCiphertext.txt");
FileOutputStream Two2 = new FileOutputStream("CryptoDeciphered.txt");
Two2.write(key.getBytes());
Two2.close();
decrypt(key, One2, Two2);
} catch (Throwable e) {
e.printStackTrace();
}
}
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);
}
public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, desKey);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}
public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
// =============================== DO NOT MODIFY ANY CODE BELOW HERE ===============================
// Compare the files
System.out.println(compareFiles() ? "The files are identical!" : "The files are NOT identical.");
}
/**
* Compares the Plaintext file with the Deciphered file.
*
* #return true if files match, false if they do not
*/
public static boolean compareFiles() throws IOException
{
Scanner pt = new Scanner(new File("CryptoPlaintext.txt")); // Open the plaintext file
Scanner dc = new Scanner(new File("CryptoDeciphered.txt")); // Open the deciphered file
// Read through the files and compare them record by record.
// If any of the records do not match, the files are not identical.
while(pt.hasNextLine() && dc.hasNextLine())
if(!pt.nextLine().equals(dc.nextLine())) return false;
// If we have any records left over, then the files are not identical.
if(pt.hasNextLine() || dc.hasNextLine()) return false;
// The files are identical.
return true;
}
}
Why the error occurs:
You invoke the method compareFiles in your copy method, which is called to copy the encrypted content of the plaintext file to the cipher text file. When this call occurs the file containing the decrypted cipher text doesn't exist but is required by the compareFiles method resulting in your exception.
How to improve your code:
you don't need the statement Two2.write(key.getBytes())
use the try-with-resource statement to automatically flush and close your streams
the standard library provides methods to copy data from a path to a stream and vice versa. Have a look at Files.copy(...) or Guava's ByteStreams.copy(...)
change your methods' throws clause, throws Throwable is just bad design to get rid of proper exception handling, if you are struggling with InvalidKeyException, NoSuchAlgorithmException, etc, catch these when you create your cipher and rethrow e.g. IllegalArgumentException or a custom exception
Here is an example how to implement it:
public class Crypto
{
public static void main(String[] args)
{
byte[] key = "B1LLYB0B".getBytes(StandardCharsets.UTF_8);
Path plaintext = Paths.get("CryptoPlaintext.txt");
Path ciphertext = plaintext.resolveSibling("CryptoCiphertext.txt");
Path decrypted = ciphertext.resolveSibling("CryptoDeciphered.txt");
try
{
// Encrypt plaintext.
try (OutputStream os = encrypt(key, Files.newOutputStream(ciphertext)))
{
Files.copy(plaintext, os);
}
// Decrypt ciphertext.
try (InputStream is = decrypt(key, Files.newInputStream(ciphertext)))
{
Files.copy(is, decrypted);
}
// TODO Compare plaintext and decrypted ciphertext.
}
catch (IOException e)
{
e.printStackTrace(); // TODO Handle exception properly.
}
}
private static OutputStream encrypt(byte[] key, OutputStream os)
{
return new CipherOutputStream(os, getCipherInstance(key, Cipher.ENCRYPT_MODE));
}
private static InputStream decrypt(byte[] key, InputStream is)
{
return new CipherInputStream(is, getCipherInstance(key, Cipher.DECRYPT_MODE));
}
private static Cipher getCipherInstance(byte[] key, int mode)
{
// TODO Implement and return the desired cipher.
}
}
By the way: Your teacher doesn't close his scanners in compareFiles() resulting in a resource leak.
I have to do encryption of text file using JCE (Java SE 1.6). For this I have written a method aes256CBCEncrypt which returns CipherOutputstream which I write in file 'encryptedtest'. Now when I am trying to do decryption of this file(named 'encryptedtest') using the method aes256CBCDecrypt, It returns me CipherInputStream which I am writing in 'decryptedtest' to verify its content. Surprisingly, this file is empty.
Can somebody help me out what is wrong with my code.
Code Snippet:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
class MyTest{
public static OutputStream aes256CBCEncrypt(OutputStream os, String passPhrase) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, InvalidKeyException, InvalidAlgorithmParameterException
{
// MessageDigest md = MessageDigest.getInstance("SHA-256");
// md.update(passPhrase.getBytes());
// byte[] key = md.digest();
Cipher aesCipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
SecureRandom secureRandom = new SecureRandom();
secureRandom.setSeed(System.currentTimeMillis());
byte[] bb = new byte[16];
secureRandom.nextBytes(bb);
os.write(bb);
aesCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(passPhrase.getBytes(), "AES"), new IvParameterSpec(
bb));
return new CipherOutputStream(os, aesCipher);
}
public static InputStream aes256CBCDecrypt(File f, String passPhrase)
throws FileNotFoundException
{
FileInputStream fis = null;
try
{
//MessageDigest md = MessageDigest.getInstance("SHA-256");
// md.update(passPhrase.getBytes());
// byte[] key = md.digest();
Cipher aesCipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
fis = new FileInputStream(f);
byte[] bb = new byte[16];
fis.read(bb);
aesCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(passPhrase.getBytes(), "AES"), new IvParameterSpec(
bb));
return new CipherInputStream(fis, aesCipher);
}
catch (final Exception e)
{
}
return null;
}
public static void main(String args[]) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IOException{
String keyFile = "C:\\contentProducer" + File.separator + "test";
String encryptedFile = "C:\\contentProducer" + File.separator + "encryptedtest";
String decryptedFile = "C:\\contentProducer" + File.separator + "decryptedtest";
FileInputStream in = new FileInputStream(keyFile);
FileOutputStream bos = new FileOutputStream(new File(encryptedFile));
//Call method for Encryption
OutputStream encryptedBos = aes256CBCEncrypt(bos,"0123456789abcdef");
int inByte;
while ((inByte = in.read()) != -1 ) {
encryptedBos.write(inByte);
}
in.close();
bos.close();
encryptedBos.close();
//Call Method for Decryption
InputStream inputStream = aes256CBCDecrypt(new File(encryptedFile), "0123456789abcdef");
FileOutputStream deos = new FileOutputStream(new File(decryptedFile));
while ((inByte = inputStream.read()) != -1 ) {
deos.write(inByte);
}
inputStream.close();
deos.close();
}
}
You are closing your FileOutputStream before you close your CipherOutputStream. This prevents the latter from completing its work and writing the encrypted data to disk.
bos.close();
encryptedBos.close();
should change to:
encryptedBos.close();
bos.close();
Program is running now. It runs but then crashes. In my files folder it creates an encrypted file but it is blank. It also does not produce a decrypted file at all. I also changed the bit size to 128. What else I am missing in order to properly implement AES?
This is the modified program
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.DESKeySpec;
public class MyCiphers {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("key.txt"));
String key = br.readLine();
br.close();
FileInputStream fis = new FileInputStream("original.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();
}
}
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);
}
public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
SecretKeySpec dks = new SecretKeySpec(key.getBytes(),"AES");
Cipher cipher = Cipher.getInstance("AES");
if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, dks);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, dks);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}
public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[128];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}
}
As the error message says, there is no method getBytes() for the type InputStream.
You need to read the key and store it as a String.
eg.
rather than FileInputStream fisk ... do
BufferedReader br = new BufferedReader(new FileReader("Key.txt"));
String key = br.readLine();
br.close();
(assuming that your key file just contains the key on one line)
Then change your encrypt/decrypt and encryptOrDecrypt methods to take in the key as a String rather than InputStream
eg. encrypt(String key, InputStream is, OutputStream os)
Then you can call SecretKeySpec(key.getBytes(),"DES");
Also you realise that this is DES, not AES as you say right? If you want to use AES you will need a 128 bit key (or 192/256 bits)
O want to encrypt and decrypt files using my Java program.
These files are compiled Java .class files, I don't know what I am doing wrong. I am just testing now, but after encrypt and decrypt with the same key. It shows that file is
Exception in thread "AWT-EventQueue-0" java.lang.ClassFormatError: Truncated class file
and that class cannot be loaded.
There is my encrypter/decrypter class code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class EncTool {
public static void encrypt(String key, String filename) throws Throwable {
InputStream is = new FileInputStream("SomeFile.class");
OutputStream os = new FileOutputStream("SomeFile.class");
encrypt(key, Cipher.ENCRYPT_MODE, is, os);
}
public static void decrypt(String key, String filename) throws Throwable {
InputStream is = new FileInputStream("SomeFile.class");
OutputStream os = new FileOutputStream("SomeFile.class");
decrypt(key, Cipher.DECRYPT_MODE, is, os);
}
public static void encrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE
cipher.init(Cipher.ENCRYPT_MODE, desKey);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
}
public static void decrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE
cipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}
}
and for testing im executing it that way:
try {
EncTool.encrypt("somekey123", "SomeFile");
EncTool.decrypt("somekey123", "SomeFile");
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
What am i doing wrong?
Or maybe how should it be done?
EDIT
when my code looks that:
public static void encrypt(String key, String filename) throws Throwable {
InputStream is = new FileInputStream("Somefile.class");
OutputStream os = new FileOutputStream("tempfile.class");
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE
cipher.init(Cipher.ENCRYPT_MODE, desKey);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
File file2 = new File("tempfile.class");
File f = new File("somefile.class");
f.delete();
file2.renameTo(f);
}
Now it works, but these deleting and renaming thing doesn't look elegant, how can I do it more efficient?
You must write the output to a new file instead of overwriting the input while you are reading it. The way your code is written now the results will be undefined.
I have an application which displays image downloaded from server. the image is encrypted and kept in the server using AES. I need to decrypt the image at the client side. The code used for encryption is as follows
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;
public class Crypto {
Cipher ecipher;
Cipher dcipher;
/**
* Input a string that will be md5 hashed to create the key.
* #return void, cipher initialized
*/
public Crypto(){
try{
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
this.setupCrypto(kgen.generateKey());
} catch (Exception e) {
e.printStackTrace();
}
}
public Crypto(String key){
SecretKeySpec skey = new SecretKeySpec(getMD5(key), "AES");
this.setupCrypto(skey);
}
private void setupCrypto(SecretKey key){
try
{ Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
ecipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
dcipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception e)
{
e.printStackTrace();
}
}
// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];
public void encrypt(InputStream in, OutputStream out){
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0){
out.write(buf, 0, numRead);
}
out.close();
}
catch (java.io.IOException e){
e.printStackTrace();
}
}
public void decrypt(InputStream in, OutputStream out){
try {
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
private static byte[] getMD5(String input){
try{
byte[] bytesOfMessage = input.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
return md.digest(bytesOfMessage);
} catch (Exception e){
return null;
}
}
public static void main(String args[]){
try {
Crypto encrypter = new Crypto("yursxjdlbkuikeqe"); ///key for decryption logic
encrypter.encrypt(new FileInputStream("D:\\Path\\Lighthouse.jpg"),new FileOutputStream("D:\\Encryption\\iOS code base\\Lighthouse.jpg.pkcs5"));
encrypter.decrypt(new FileInputStream("D:\\Path\\Lighthouse.jpg.pkcs5"),new FileOutputStream("D:\\Encryption\\iOS code base\\Lighthouse.jpg"));
System.out.println("DONE");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I am not able to decrypt this using Blackberry AESDecryptor Engine. I am new to this crypto graphy. Is it possible to decrypt using AESDecryptor engine. I am attaching the code which I am using. Please help me in solving this
public MyScreen(){
// Set the displayed title of the screen
setTitle("MyTitle");
byte[] keyData = new String("yursxjdlbkuikeqe").getBytes();
byte[] cipherText = openFile("file:///SDCard/Lighthouse.jpg.pkcs5");
try {
imageData = decrypt(keyData, cipherText);
} catch (CryptoException e) {
System.out.println("::::::::::::::::::::::::::::::::::Crypto Exception:::::::"+e.getMessage());
} catch (IOException e) {
System.out.println("::::::::::::::::::::::::::::::::::IO Exception:::::::"+e.getMessage());
}
if(imageData!=null){
writeByteData(imageData);
// EncodedImage image = EncodedImage.createEncodedImage(imageData, 0, imageData.length);
// add(new BitmapField(image.getBitmap()));
System.out.println("------------------Image saved successfully-----------");
}else{
System.out.println("-------------------Image Data is null");
}
}
public static byte[] decrypt(byte[] keyData, byte[] ciphertext) throws CryptoException, IOException {
// First, create the AESKey again.
/*String str=new String(keyData);
System.out.println(str);*/
AESKey key = new AESKey(keyData,0,128);
System.out.println("Key is ::"+key.getAlgorithm()+"Length:"+key.getBitLength());
//
// // Now, create the decryptor engine.
AESDecryptorEngine engine = new AESDecryptorEngine(key);
PKCS5UnformatterEngine uengine = new PKCS5UnformatterEngine(engine);
/
// // Create the BlockDecryptor to hide the decryption details away.
ByteArrayInputStream input = new ByteArrayInputStream(ciphertext);
BlockDecryptor decryptor = new BlockDecryptor(engine, input);
byte[] plaintextAndHash = new byte[1024];
ByteArrayOutputStream output = new ByteArrayOutputStream();
int bytesRead=0;
do{
bytesRead =decryptor.read(plaintextAndHash);
if(bytesRead!=-1){
output.write(plaintextAndHash,0,bytesRead);
}
}
while(bytesRead!=-1);
return output.toByteArray();
}
You don't really say what your problem is, but at least the following line looks incorrect:
BlockDecryptor decryptor = new BlockDecryptor(engine, input);
It should be
BlockDecryptor decryptor = new BlockDecryptor(uengine, input);
I just changed engine to uengine
RIM's APIs make this pretty easy but it is a little tough to find the documentation. Check out the Javadocs for the package net.rim.device.api.crypto at:
http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/crypto/package-summary.html
You should look through all of it but the answer is in number 7: Encryptor and decryptor factories.
http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/crypto/doc-files/factories.html
The DecryptorFactory can create an input stream that you can just read as any InputStream.