如何使用Bouncy Castle Crypto API来加密和解密数据

Bouncy Castle Crypto API 是用JAVA编写的一套轻量级的加密API.同时,它也包括一个支持J2ME的版本.本例将介绍如何使用Bouncy Castle Crypto API来加密和解密数据

下边的Encryptor类允许你使用encryptString and decryptString方法加密和解密任意的数据:

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

// 一个简单的例子说明了如何使用Bouncy Castle
// 加密API来执行对任意数据的DES加密

public class Encryptor {
   
    private BufferedBlockCipher cipher;
    private KeyParameter key;
   
    // 初始化加密引擎.
    // 数组key的长度至少应该是8个字节.
   
    public Encryptor( byte[] key ){
        /*
        cipher = new PaddedBlockCipher(
                 new CBCBlockCipher(
                 new DESEngine() ) );
         */
       
        cipher = new PaddedBlockCipher(
                new CBCBlockCipher(
                new BlowfishEngine() ) );
       
        this.key = new KeyParameter( key );
    }
   
     // 初始化加密引擎.
    // 字符串key的长度至少应该是8个字节.
   
    public Encryptor( String key ){
        this( key.getBytes() );
    }
   
    // 做加密解密的具体工作
   
    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( data );
    }
   
    // 加密一个字符串
   
    public byte[] encryptString( String data )
    throws CryptoException {
        if( data == null || data.length() == 0 ){
            return new byte[0];
        }
       
        return encrypt( data.getBytes() );
    }
   
    // 解密一个字节数组
   
    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 ) );
    }
}


 

下边的代码演示如何使用上边的Encryptor类来加密解密数据

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, 1 );
    private Command okCommand = new Command( "OK", Command.OK, 1 );
   
    private Encryptor   encryptor;
    private RecordStore rs;
   
    /** 构造函数*/
    public CryptoTest() {
    }
   
    private void initialize() {
    }
   
    public void startApp() {
        initialize();
        if( display == null ){ // first time called...
            initMIDlet();
        }
    }
   
    public void pauseApp() {
    }
   
    public void destroyApp(boolean unconditional) {
        exitMIDlet();
    }
   
    private void initMIDlet(){
        display = Display.getDisplay( this );
       
        // 打开名为"test3"的RecordStore      
        try {
            rs = RecordStore.openRecordStore( "test3",
                    true );
        } catch( RecordStoreException e ){
        }
       
        display.setCurrent( new AskForKey() );
    }
   
    public void exitMIDlet(){
        try {
            if( rs != null ){
                rs.closeRecordStore();
            }
        } catch( RecordStoreException e ){
        }
       
        notifyDestroyed();
    }
   
    private void displayException( Exception e ){
        Alert a = new Alert( "Exception" );
        a.setString( e.toString() );
        a.setTimeout( Alert.FOREVER );
        display.setCurrent( a, new AskForKey() );
    }
   
    class AskForKey extends TextBox
            implements CommandListener {
        public AskForKey(){
            super( "Enter a secret key:", "", 8, 0 );
            setCommandListener( this );
            addCommand( okCommand );
            addCommand( exitCommand );
        }
       
        public void commandAction( Command c,
                Displayable d ){
            if( c == exitCommand ){
                exitMIDlet();
            }
           
            String key = getString();
            if( key.length() < 8 ){
                Alert a = new Alert( "Key too short" );
                a.setString( "The key must be " +
                        "8 characters long" );
                setString( "" );
                display.setCurrent( a, this );
                return;
            }
           
            encryptor = new Encryptor( key );
           
            try {
                if( rs.getNextRecordID() == 1 ){
                    display.setCurrent(
                            new EnterMessage() );
                } else {
                    byte[] data = rs.getRecord( 1 );
                    String str =
                            encryptor.decryptString( data );
                   
                    Alert a =
                            new Alert( "Decryption" );
                    a.setTimeout( Alert.FOREVER );
                    a.setString(
                            "The decrypted string is '" +
                            str + "'" );
                    display.setCurrent( a, this );
                }
            } catch( RecordStoreException e ){
                displayException( e );
            } catch( CryptoException e ){
                displayException( e );
            }
        }
    }
   
    class EnterMessage extends TextBox
            implements CommandListener {
        public EnterMessage(){
           
           
            super( "Enter a message to encrypt:", "",
                    100, 0 );
           
            BigInteger bigInt = new BigInteger("199999");
           
            setCommandListener( this );
            addCommand( okCommand );
        }
       
        public void commandAction( Command c,
                Displayable d ){
            String msg = getString();
           
            try {
                byte[] data =
                        encryptor.encryptString( msg );
                rs.addRecord( data, 0, data.length );
            } catch( RecordStoreException e ){
                displayException( e );
            } catch( CryptoException e ){
                displayException( e );
            }
           
            display.setCurrent( new AskForKey() );
        }
    }
   

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/the3gwireless/archive/2006/04/24/674500.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值