java left logo
java middle logo
java right logo
 

Home arrow Java ME Tips
 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 3942
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
Encrypting/Decrypting text messages with Bouncy Castle Crypto API E-mail
User Rating: / 83
PoorBest 

Bouncy Castle Crypto API is a lightweight cryptography API in Java. It also have a J2ME version. This tip will give you an example of encryption and decryption of messages using Bouncy Castle Crypto API.

Let’s start with the utility class we will use in our midlet to encrypt/decrypt arbitrary text messages. Encryptor class below allows you to encrypt and decrypt arbitrary messages using encryptString and decryptString methods:

import org.bouncycastle.crypto.*;
import org.bouncycastle.crypto.engines.*;
import org.bouncycastle.crypto.modes.*;
import org.bouncycastle.crypto.params.*;

// A simple example that uses the Bouncy Castle
// lightweight cryptography API to perform DES
// encryption of arbitrary data.

public class Encryptor {
    
    private BufferedBlockCipher cipher;
    private KeyParameter key;
    
    // Initialize the cryptographic engine.
    // The key array should be at least 8 bytes long.
    
    public Encryptorbyte[] key ){
        /*
        cipher = new PaddedBlockCipher(
                 new CBCBlockCipher(
                 new DESEngine() ) );
         */
        
        cipher = new PaddedBlockCipher(
                new CBCBlockCipher(
                new BlowfishEngine() ) );
        
        this.key = new KeyParameterkey );
    }
    
    // Initialize the cryptographic engine.
    // The string should be at least 8 chars long.
    
    public EncryptorString key ){
        thiskey.getBytes() );
    }
    
    // Private routine that does the gritty work.
    
    private byte[] callCipherbyte[] data )
    throws CryptoException {
        int    size =
                cipher.getOutputSizedata.length );
        byte[] result = new bytesize ];
        int    olen = cipher.processBytesdata, 0,
                data.length, result, );
        olen += cipher.doFinalresult, olen );
        
        ifolen < size ){
            byte[] tmp = new byteolen ];
            System.arraycopy(
                    result, 0, tmp, 0, olen );
            result = tmp;
        }
        
        return result;
    }
    
    // Encrypt arbitrary byte array, returning the
    // encrypted data in a different byte array.
    
    public synchronized byte[] encryptbyte[] data )
    throws CryptoException {
        ifdata == null || data.length == ){
            return new byte[0];
        }
        
        cipher.inittrue, key );
        return callCipherdata );
    }
    
    // Encrypts a string.
    
    public byte[] encryptStringString data )
    throws CryptoException {
        ifdata == null || data.length() == ){
            return new byte[0];
        }
        
        return encryptdata.getBytes() );
    }
    
    // Decrypts arbitrary data.
    
    public synchronized byte[] decryptbyte[] data )
    throws CryptoException {
        ifdata == null || data.length == ){
            return new byte[0];
        }
        
        cipher.initfalse, key );
        return callCipherdata );
    }
    
    // Decrypts a string that was previously encoded
    // using encryptString.
    
    public String decryptStringbyte[] data )
    throws CryptoException {
        ifdata == null || data.length == ){
            return "";
        }
        
        return new Stringdecryptdata ) );
    }
}


And here is the source of our midlet which uses Encryptor class described above to encrypt/decrypt messages entered by the user:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;

import org.bouncycastle.crypto.*;

import java.math.BigInteger;

public class CryptoTest extends MIDlet {
    
    private Display display;
    private Command exitCommand = new Command"Exit", Command.EXIT, );
    private Command okCommand = new Command"OK", Command.OK, );
    
    private Encryptor   encryptor;
    private RecordStore rs;
    
    /** Creates a new instance of CryptoTest */
    public CryptoTest() {
    }
    
    /**
     * This method initializes UI of the application.
     */
    private void initialize() {
    }
    
    public void startApp() {
        initialize();
        ifdisplay == null ){ // first time called...
            initMIDlet();
        }
    }
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
        exitMIDlet();
    }
    
    private void initMIDlet(){
        display = Display.getDisplaythis );
        
        // Open a record store here        
        try {
            // This need to be changed to start with a clean reocrd
            rs = RecordStore.openRecordStore"test3",
                    true );
        catchRecordStoreException e ){
            // put in error handling here
        }
        
        display.setCurrentnew AskForKey() );
    }
    
    public void exitMIDlet(){
        try {
            ifrs != null ){
                rs.closeRecordStore();
            }
        catchRecordStoreException e ){
        }
        
        notifyDestroyed();
    }
    
    private void displayExceptionException e ){
        Alert a = new Alert"Exception" );
        a.setStringe.toString() );
        a.setTimeoutAlert.FOREVER );
        display.setCurrenta, new AskForKey() );
    }
    
    class AskForKey extends TextBox
            implements CommandListener {
        public AskForKey(){
            super"Enter a secret key:"""8);
            setCommandListenerthis );
            addCommandokCommand );
            addCommandexitCommand );
        }
        
        public void commandActionCommand c,
                Displayable d ){
            ifc == exitCommand ){
                exitMIDlet();
            }
            
            String key = getString();
            ifkey.length() ){
                Alert a = new Alert"Key too short" );
                a.setString"The key must be " +
                        "8 characters long" );
                setString"" );
                display.setCurrenta, this );
                return;
            }
            
            encryptor = new Encryptorkey );
            
            try {
                ifrs.getNextRecordID() == ){
                    display.setCurrent(
                            new EnterMessage() );
                else {
                    byte[] data = rs.getRecord);
                    String str =
                            encryptor.decryptStringdata );
                    
                    Alert a =
                            new Alert"Decryption" );
                    a.setTimeoutAlert.FOREVER );
                    a.setString(
                            "The decrypted string is '" +
                            str + "'" );
                    display.setCurrenta, this );
                }
            catchRecordStoreException e ){
                displayException);
            catchCryptoException e ){
                displayException);
            }
        }
    }
    
    class EnterMessage extends TextBox
            implements CommandListener {
        public EnterMessage(){
            
            
            super"Enter a message to encrypt:""",
                    100);
            
            BigInteger bigInt = new BigInteger("199999");
            
            setCommandListenerthis );
            addCommandokCommand );
        }
        
        public void commandActionCommand c,
                Displayable d ){
            String msg = getString();
            
            try {
                byte[] data =
                        encryptor.encryptStringmsg );
                rs.addRecorddata, 0, data.length );
            catchRecordStoreException e ){
                displayException);
            catchCryptoException e ){
                displayException);
            }
            
            display.setCurrentnew AskForKey() );
        }
    }
    
}

Also note at the time of this writing that some version of Bouncy Castle Crypto API is not compiled for MIDP 2.0. When you tried to compile this example with Bouncy Castle Crypto API, you may get errors. (Some of the test classes use some classes not available to J2ME which is only available to J2SE) In that case, you may try other versions of the API to eliminate this problem.

If the above method still does not work for you, we recommend you to add full source code of the API to your project and eliminate problems one by one by removing some test classes and removing unnecessary but problematic parts of the library. (Note that you should also check the license before distributing the changes you made!)

References
  1. The Legion of the Bouncy Castle

 Related Tips


 Related Tips

 
< Prev   Next >

Page 1 of 0 ( 0 comments )

You can share your information about this topic using the form below!

Please do not post your questions with this form! Thanks.


Name (required)


E-Mail (required)

Your email will not be displayed on the site - only to our administrator
Homepage(optional)



Comment Enable HTML code : Yes No



 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.