用Bouncy Castle实现AES_128_CBC在j2se和j2me上的加密解密

本文介绍了如何利用Bouncy Castle Crypto APIs这一开源轻量级Java加密库,在j2se和j2me环境中实现AES_128_CBC的加密解密。提供了使用JCE和不使用JCE的示例代码,以及将其实现为工具类的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Bouncy Castle Crypto APIs 是一个开源的轻量级Java 加密解密包,实现了JCE/JCA的provider,支持AES等多种加密解密算法。
详情请见主页:http://www.bouncycastle.org/java.html
本文的示例代码使用了http://www.bouncycastle.org/download/bcprov-jdk16-139.jar
1)使用JCE的AES-128-CBC加密解密(j2se)

 

 

package com.albertsong.aes;

import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

public class AESWithJCE {

    /**
     * @param args
     */
    public static void main(String[] args) {
        byte[] keybytes = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
                0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };
        byte[] iv = { 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x38,
                0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31 };
        String content ="TEST1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        System.out.println("Original content:");
        System.out.println(content);
        try {
            Security.addProvider(new BouncyCastleProvider());
            Key key = new SecretKeySpec(keybytes, "AES");
            Cipher in = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            in.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
            byte[] enc = in.doFinal(content.getBytes());
            System.out.println("Encrypted Content:");
            System.out.println(new String(Hex.encode(enc)));
            
            Cipher out = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            out.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
            byte[] dec = out.doFinal(enc);
            System.out.println("Decrypted Content:");
            System.out.println(new String(dec));
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

}

2)不使用JCE的AES-128-CBC加密解密,可以用于J2ME程序中。

package com.albertsong.aes;

import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Hex;

/**
 * @author Albert
 * @version 1.0
 *
 */
public class AESWithoutJCE {

    /**
     * @param args
     */
    public static void main(String[] args) {
        byte[] keybytes = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
                0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };
        byte[] iv = { 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x38,
                0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31 };
        String content ="TEST1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        System.out.println("Original content:");
        System.out.println(content);
        try {
            BufferedBlockCipher engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
            engine.init(true, new ParametersWithIV(new KeyParameter(keybytes),iv));
            byte[] enc = new byte[engine.getOutputSize(content.getBytes().length)];
            int size1 = engine.processBytes(content.getBytes(), 0, content.getBytes().length, enc, 0);
            int size2 = engine.doFinal(enc, size1);
            System.out.println("size2 ="+size2);
            byte[] encryptedContent =new byte[size1+size2];
            System.arraycopy(enc, 0, encryptedContent, 0, encryptedContent.length);
            System.out.println("Encrypted Content:");
            System.out.println(new String(Hex.encode(encryptedContent)));
            
            
            engine.init(false, new ParametersWithIV(new KeyParameter(keybytes),iv));
            byte[] dec = new byte[engine.getOutputSize(encryptedContent.length)];
            size1 = engine.processBytes(encryptedContent, 0, encryptedContent.length, dec, 0);
            size2 = engine.doFinal(dec, size1);
            System.out.println("size2 ="+size2);
            byte[] decryptedContent =new byte[size1+size2];
            System.arraycopy(dec, 0, decryptedContent, 0, decryptedContent.length);
            System.out.println("Decrypted Content:");
            System.out.println(new String(decryptedContent));

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

}



3.用作一个工具类,传入明文或密码分别实现加密解密

package com.albertsong.aes;

import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Hex;

public class AES_128_CBC {
	
    static byte[] keybytes = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
            0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };
    static byte[] iv = { 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x38,
            0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31 };
    
	/**
	 * 
	 * @param content 需要加密的内容
	 * @return 密文
	 * @throws Exception
	 */
	public static String Encrypt(String content) throws Exception{
        BufferedBlockCipher engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        engine.init(true, new ParametersWithIV(new KeyParameter(keybytes),iv));
        byte[] enc = new byte[engine.getOutputSize(content.getBytes().length)];
        int size1 = engine.processBytes(content.getBytes(), 0, content.getBytes().length, enc, 0);
        int size2 = engine.doFinal(enc, size1);
        System.out.println("size2 ="+size2);
        byte[] encryptedContent =new byte[size1+size2];
        System.arraycopy(enc, 0, encryptedContent, 0, encryptedContent.length);
        System.out.println("Encrypted Content:");
		String key = new String(Hex.encode(encryptedContent));
		System.out.println(key);
        return key;
	}
	
	/**
	 * 
	 * @param Key 密文
	 * @return 明文
	 * @throws Exception
	 */
	public static String Decrypt(String Key) throws Exception {
		byte[] encryptedContent = hex2byte(Key);
        BufferedBlockCipher engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));

        engine.init(false, new ParametersWithIV(new KeyParameter(keybytes),iv));
        byte[] dec = new byte[engine.getOutputSize(encryptedContent.length)];
        int size1 = engine.processBytes(encryptedContent, 0, encryptedContent.length, dec, 0);
        int size2 = engine.doFinal(dec, size1);
        System.out.println("size2 ="+size2);
        byte[] decryptedContent =new byte[size1+size2];
        System.arraycopy(dec, 0, decryptedContent, 0, decryptedContent.length);
        System.out.println("Decrypted Content:");
        System.out.println(new String(decryptedContent));
		String content = new String(new String(decryptedContent));
        return content;
	}
	
	
	public static byte[] hex2byte(String strhex) {
		if (strhex == null) {
			return null;
		}
		int l = strhex.length();
		if (l % 2 == 1) {
			return null;
		}
		byte[] b = new byte[l / 2];
		for (int i = 0; i != l / 2; i++) {
			b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
					16);
		}
		return b;
	}
	
	public static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
		}
		return hs.toUpperCase();
	}
	
    public static void main(String[] args) {

        String content ="偶像Jordan";
//        String content = "KaRant is The Best !!";
        System.out.println("Original content:");
        System.out.println(content);
        String enc = null;
        try {
			enc = Encrypt(content);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        try {
			new String(Decrypt(enc));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值