开发者

Port Java-SE encryption code to BlackBerry

开发者 https://www.devze.com 2023-01-06 04:03 出处:网络
I have the following encrypt / decrypt routines and need to port them to my BlackBerry project.Can you please get me started?

I have the following encrypt / decrypt routines and need to port them to my BlackBerry project. Can you please get me started?

import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

 public String EncryptData(String data, String skey) throws Exception {      
    String encryptedData = "";        

    try{
       byte [] bData = data.getBytes();
       String alg = "AES/ECB/NoPadding"; 
       SecretKey key = new SecretKeySpec(skey.getBytes(), alg.replaceFirst("/.*", "")); 
       Cipher cipher = Cipher.getInstance(alg);
       cipher.init(Cipher.ENCRYPT_MODE, key);
       byte[开发者_Go百科] encoded = cipher.doFinal(bData);          
       encryptedData = bytesToHex(encoded);
    }
    catch(Exception e){
        throw e;
    }
    return encryptedData;
}



public String DecryptData(String hexString, String skey) throws Exception {

    String decryptedData = "";
    try{
       byte [] bData =  convToBinary(hexString);

       String alg = "AES/ECB/NoPadding";            
       SecretKey key = new SecretKeySpec(skey.getBytes(), alg.replaceFirst("/.*", ""));           
       Cipher cipher = Cipher.getInstance(alg);
       cipher.init(Cipher.DECRYPT_MODE, key);
       byte[] decoded = cipher.doFinal(bData);
       decryptedData = new String(decoded);
    }
    catch(Exception e){
        throw e;
    }
    return decryptedData;
}


I would suggest maybe looking through the API documentation for the JDE you are using, in particular I would guess the net.rim.device.api.crypto package would probably be of most interest to you.

net.rim.device.api.crypto.Crypto might also be a good class to look into since it contains static methods for encrypting and decrypting.


Managed to get it working...

byte[] keyData = keyString.getBytes();

    AESKey key = new AESKey(keyData);
    NoCopyByteArrayOutputStream out = new NoCopyByteArrayOutputStream();
    AESEncryptorEngine engine = new AESEncryptorEngine(key);
    BlockEncryptor encryptor = new BlockEncryptor(engine, out);
    encryptor.write(data, 0, data.length);
    int finalLength = out.size();

    byte[] cbytes = new byte[finalLength];
    System.arraycopy(out.getByteArray(), 0, cbytes, 0, finalLength);
    encryptedData = bytesToHex(cbytes);
    return encryptedData;
0

精彩评论

暂无评论...
验证码 换一张
取 消