📄 bccipher.java
字号:
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -