Java AES-256-CBC ZeroPadding

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;

/**
 * @author alderaan
 */
public class AES32CBCNoPadding {
    public static byte[] IV="0000000000000000".getBytes();
    public static final String KEY_ALGORITHM = "AES";
    public static final String CIPHER_ALGORITHM_CBC = "AES/CBC/NoPadding";

    public static byte[] encrypt(byte[] data, byte[] key) throws Exception {

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
        int blockSize = cipher.getBlockSize();
        int length = data.length;
        // 计算需填充长度
        if (length % blockSize != 0) {
            length = length + (blockSize - (length % blockSize));
        }
        byte[] plaintext = new byte[length];
        // 拷贝数据
        System.arraycopy(data, 0, plaintext, 0, data.length);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(autoKey(key), KEY_ALGORITHM), new IvParameterSpec(IV));
        return cipher.doFinal(plaintext);
    }

    public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(autoKey(key), KEY_ALGORITHM), new IvParameterSpec(IV));
        return cipher.doFinal(data);
    }


    private static byte[] autoKey(byte[] key){
        byte[] bytes = new byte[32];
        for (int i =0;i<32;i++){
            bytes[i]=0;
        }
        if (key.length>=32){
            System.arraycopy(key,0,bytes,0,32);
        }else {
            System.arraycopy(key,0,bytes,0,key.length);
        }
        return bytes;

    }

    public static String randomKey(int len){
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i =0;i<len;i++){
            stringBuilder.append(String.valueOf((char)(random.nextInt(94)+32)));
        }
        return stringBuilder.toString();
    }
    
    public static void main(String[] argv){
    	// 随机一个key 长度指定为3
    	String key = randomKey(3);
    	try {
    		// 对字符串123进行加密
			byte[] temp = encrypt("plaintext...".getBytes(),key.getBytes());
			// 解密并输出解密后的结果
			System.out.println(new String(decrypt(temp,key.getBytes())));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值