Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Taken from: http://stackoverflow.com/questions/8731671/aesdecryption-in-blackberry
- */
- import javax.crypto.*;
- import javax.crypto.spec.SecretKeySpec;
- import java.io.*;
- import java.security.NoSuchAlgorithmException;
- import java.security.MessageDigest;
- import java.security.*;
- class AESDemo {
- private static Cipher eCipher, dCipher;
- private static byte[] buf = new byte[1024];
- 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;
- }
- }
- private static void init_crypto(String key){
- SecretKeySpec skey = new SecretKeySpec(getMD5(key), "AES");
- 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, skey);
- dCipher.init(Cipher.DECRYPT_MODE, skey);
- }
- catch (Exception e){
- e.printStackTrace();
- }
- }
- public static void encrypt(File fin, File fout){
- try {
- InputStream in = new FileInputStream(fin);
- OutputStream out = new FileOutputStream(fout);
- out = new CipherOutputStream(out, eCipher);
- int numRead = 0;
- while ((numRead = in.read(buf)) >= 0){
- out.write(buf, 0, numRead);
- }
- out.close();
- }
- catch (IOException e){
- e.printStackTrace();
- }
- }
- public static void decrypt(File fin, File fout){
- try {
- InputStream in = new FileInputStream(fin);
- OutputStream out = new FileOutputStream(fout);
- in = new CipherInputStream(in, dCipher);
- int numRead = 0;
- while ((numRead = in.read(buf)) >= 0) {
- out.write(buf, 0, numRead);
- }
- out.close();
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static byte[] readFile(File file) throws IOException {
- byte []buffer = new byte[(int) file.length()];
- InputStream ios = null;
- try {
- ios = new FileInputStream(file);
- if ( ios.read(buffer) == -1 ) {
- throw new IOException("EOF reached while trying to read the whole file");
- }
- }
- finally {
- try {
- if ( ios != null ) ios.close();
- }
- catch ( IOException e) {
- }
- }
- return buffer;
- }
- public static void main(String args[]) throws IOException, Exception{
- String mode = args[0];
- init_crypto("Hello world");
- if (mode.equals("-e")) encrypt(new File(args[1]), new File(args[2]));
- else if (mode.equals("-d")) decrypt(new File(args[1]), new File(args[2]));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement