bccipher.java

来自「用Java/C#开发手机程序及移动应用光盘代码。J2ME核心类及MIDlet类;」· Java 代码 · 共 75 行

JAVA
75
字号
import org.bouncycastle.crypto.*;
import org.bouncycastle.crypto.engines.*;
import org.bouncycastle.crypto.modes.*;
import org.bouncycastle.crypto.params.*;

public class BCCipher
{
	private BufferedBlockCipher cipher;
	private KeyParameter key;

	// 初始化,注意key至少要8字节
	public BCCipher( byte [] key )
	{

		cipher = new PaddedBlockCipher(
				new CBCBlockCipher( new DESEngine() ) );

		this.key = new KeyParameter( key );
	}

	// 初始化,注意key至少要8字节
	public BCCipher( String key )
	{
		this( key.getBytes() );
	}

	// 加密的辅助函数
	private byte[] callCipher( boolean encipher, byte[] data)
		throws InvalidCipherTextException
	{
		cipher.init( true, key); 

		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 );
		//System.out.println( data.length +","+size+","+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
	{
		return callCipher( true, data );
	}

	// 解密
	public synchronized byte[] decrypt( byte [] data )
		throws CryptoException
	{
		return callCipher( false, data );
	}

	public synchronized String encrypt( String data )
		throws CryptoException
	{
		return new String( encrypt( data.getBytes()));
	}

	public synchronized String decrypt( String data )
		throws CryptoException
	{
		return new String( encrypt( data.getBytes()));
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?