×

Discussion Board

Results 1 to 7 of 7
  1. #1
    Regular Contributor
    Join Date
    Mar 2007
    Posts
    75

    Encrypt and Encode into writable format! HEEELP...

    Hi,
    I am trying to use bouncycastle to create a String that is a result of an encription using a numeric key and a numeric (long) to be encripted. The result, I hope, should be readable and writable using the phone standard chars (prefer them to be just num and alphanum).
    Unfortunately when I get the encryption String it could be anything (I suppose any ASCII char). when I use the getbytes to handle the encryption I specify "UTF8", this, I heard, to avoid at decryption time to get the infamous "last block..." error.

    The example gets a key a code (I insert numeric) and gives you an encrypted result. What I will do is use the encrypted result put it in the form with the same key and change the method (at commandaction) from encrypt to decript hoping to get the numeric I put in the code field in the first place.

    This is the code for the Encrypter:

    import org.bouncycastle.crypto.*;
    import org.bouncycastle.util.encoders.Base64;
    import org.bouncycastle.crypto.engines.*;
    import org.bouncycastle.crypto.modes.*;
    import org.bouncycastle.crypto.params.*;
    import org.bouncycastle.crypto.paddings.*;
    import java.io.UnsupportedEncodingException;

    public class Encrypter {

    private PaddedBufferedBlockCipher cipher;
    private KeyParameter key;

    // Initialize the cryptographic engine.
    // The key array should be at least 8 bytes long.

    public Encrypter( byte[] key ){
    /*
    cipher = new PaddedBufferedBlockCipher(
    new CBCBlockCipher(
    new DESEngine() ) );

    */
    cipher = new PaddedBufferedBlockCipher(
    new CBCBlockCipher(
    new BlowfishEngine() ) );

    this.key = new KeyParameter( key );
    }


    private byte[] callCipher( byte[] data )
    throws CryptoException {
    int size =
    cipher.getOutputSize( data.length );
    byte[] result = new byte[ size ];
    int olen = cipher.processBytes( data, 0,
    data.length, result, 0 );
    olen += cipher.doFinal( result, olen );

    if( olen < size ){
    byte[] tmp = new byte[ olen ];
    System.arraycopy(
    result, 0, tmp, 0, olen );
    result = tmp;
    }

    return result;
    }


    public synchronized byte[] encrypt( byte[] data )
    throws CryptoException {
    if( data == null || data.length == 0 ){
    return new byte[0];
    }

    cipher.init( true, key );
    return callCipher( new Base64().encode(data) );
    }

    // Encrypts a string.

    public byte[] encryptString( String data )
    throws CryptoException {
    if( data == null || data.length() == 0 ){
    return new byte[0];
    }

    return encrypt( new Base64().encode(data.getBytes()) );
    }

    // Decrypts arbitrary data.

    public synchronized byte[] decrypt( byte[] data )
    throws CryptoException {
    if( data == null || data.length == 0 ){
    return new byte[0];
    }

    cipher.init( false, key );
    return callCipher( data );
    }

    public String decryptString( byte[] data )
    throws CryptoException {
    if( data == null || data.length == 0 ){
    return "";
    }

    return new String( decrypt( data ) );
    }
    }
    This is the Midlet code:
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import org.bouncycastle.crypto.CryptoException;
    import java.io.UnsupportedEncodingException;

    public class CriptoTest extends MIDlet implements CommandListener {

    public CriptoTest() {
    initialize();
    }

    private Form form1;
    private TextField textField1;
    private TextField textField2;
    private Command okCommand1;
    private TextField textField3;
    private Encrypter cript;

    public void commandAction(Command command, Displayable displayable) {
    // Insert global pre-action code here
    if (displayable == form1) {
    if (command == okCommand1) {
    // Insert pre-action code here
    if (this.get_textField1().getString().length()==8) {
    try {
    this.cript = new Encrypter(this.get_textField1().getString().getBytes("UTF8"));

    this.get_textField2().setString(new String(this.cript.encrypt(this.get_textField3().getString().getBytes("UTF8")), "UTF8"));
    } catch (CryptoException ce) {ce.printStackTrace();}
    catch (UnsupportedEncodingException ue) {ue.printStackTrace();}
    } else {
    Alert alert = new Alert("Warning", "8 letters", null, AlertType.INFO);
    getDisplay().setCurrent(alert, this.getDisplay().getCurrent());
    }
    }
    }

    }

    /** This method initializes UI of the application.
    */
    private void initialize() {
    // Insert pre-init code here
    getDisplay().setCurrent(get_form1());
    // Insert post-init code here
    }

    public Display getDisplay() {
    return Display.getDisplay(this);
    }

    public void exitMIDlet() {
    getDisplay().setCurrent(null);
    destroyApp(true);
    notifyDestroyed();
    }

    public Form get_form1() {
    if (form1 == null) {
    // Insert pre-init code here
    form1 = new Form(null, new Item[] {
    get_textField1(),
    get_textField3(),
    get_textField2()
    });
    form1.addCommand(get_okCommand1());
    form1.setCommandListener(this);

    }
    return form1;
    }

    public TextField get_textField1() {
    if (textField1 == null) {
    // Insert pre-init code here
    textField1 = new TextField("Key", null, 8, TextField.NUMERIC);
    // Insert post-init code here
    }
    return textField1;
    }
    public TextField get_textField2() {
    if (textField2 == null) {
    // Insert pre-init code here
    textField2 = new TextField("Activation code", null, 120, TextField.ANY);
    // Insert post-init code here
    }
    return textField2;
    }

    public Command get_okCommand1() {
    if (okCommand1 == null) {
    // Insert pre-init code here
    okCommand1 = new Command("Ok", Command.OK, 1);
    // Insert post-init code here
    }
    return okCommand1;
    }

    public TextField get_textField3() {
    if (textField3 == null) {
    // Insert pre-init code here
    textField3 = new TextField("Code", null, 120, TextField.ANY);
    // Insert post-init code here
    }
    return textField3;
    }

    public void startApp() {
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    }

  2. #2
    Regular Contributor
    Join Date
    Aug 2006
    Posts
    307

    Re: Encrypt and Encode into writable format! HEEELP...

    I guess the Base64 encoding will help you: http://kobjects.sourceforge.net/utils/ It simply will neutralize special characters in encrypted string (which may contain "any" ASCII symbols), so you'll be able to read or display it.

    However, the result wouldn't be just an ASCII string, but rather an ASCII-characters array, which will allow you to safely store or send it via HTTP without any "special character trouble".

  3. #3
    Regular Contributor
    Join Date
    Mar 2007
    Posts
    75

    Re: Encrypt and Encode into writable format! HEEELP...

    I guess this will help but will I be able to go back from the encoded string to the original string (with special characters) via the decode function?
    This is what I mean:

    f(key, long)->string (this will be an encryption that gives me a String with special chars)
    encode(string)->string_en
    decode(string_en)->string
    reverseF(key, string)-> long

  4. #4
    Regular Contributor
    Join Date
    Aug 2006
    Posts
    307

    Re: Encrypt and Encode into writable format! HEEELP...

    Base64 is encoder/decoder. With encoding you'll get a StringBuffer, with decoding you'll have a byte[] array. The original string "recreation" will be quite simple: String(byte[] bytes) or String(byte[] bytes, "encoding name").

  5. #5
    Regular Contributor
    Join Date
    Mar 2007
    Posts
    75

    Re: Encrypt and Encode into writable format! HEEELP...

    That's great I'll try it right away....

    Cheers

    Alex

  6. #6
    Regular Contributor
    Join Date
    Mar 2007
    Posts
    75

    Re: Encrypt and Encode into writable format! HEEELP...

    This is great....
    I now have encoded and decoded but....
    I can't decrypt. I am pretty sure it's the fact that I am using getBytes all over the place but it seems to woek until I decrypt.
    This is the code failing with a pad block corrupted (it is the byte array length...)
    try {
    this.cript = new Encrypter(this.get_textField1().getString().getBytes("UTF8"));

    byte[] string = this.cript.encrypt(this.get_textField3().getString().getBytes("UTF8"));

    this.get_textField4().setString(new String (string, "UTF8"));

    StringBuffer string_en = cripto.Base64.encode(string,0,string.length,null);

    this.get_textField2().setString(string_en.toString());

    String string_de = new String(cripto.Base64.decode(string_en.toString()),"UTF8");

    this.get_textField5().setString(string_de);

    byte[] string_rev = this.cript.decrypt(string_de.getBytes("UTF8"));<----

    this.get_textField6().setString(new String(string_rev, "UTF8"));

    } catch (CryptoException ce) {ce.printStackTrace();}
    catch (UnsupportedEncodingException ue) {ue.printStackTrace();}

  7. #7
    Regular Contributor
    Join Date
    Aug 2006
    Posts
    307

    Re: Encrypt and Encode into writable format! HEEELP...

    The reasons for this might be in quite many places. Some phones are not using the "UTF-8" encoding by default for representing text data, so forcing data convertions into the "UTF-8" will mess your data.

    Some mobile platforms are not able to convert strings correctly into the other encodings by using the method "getBytes". The reasons might be in implementation or sometimes even in compiler's optimizing techniques.

    Also try this: correctly_encoded_utf_8_string = new String(old_string.getBytes(), "UTF-8");

    If nothing will work, then try to run the same code, but simply without any encodings.

    Hope this will help you.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×