Java AES-256-CBC ZeroPadding

本文介绍了一个使用AES-256 CBC模式实现的加解密类,该类采用NoPadding填充方式,并提供了自动补足密钥长度的功能。通过随机生成密钥并演示了对字符串进行加密及解密的过程。
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();
		}
    }
}
Java中,使用AES (Advanced Encryption Standard) 进行ECB (Electronic Codebook) 模式加密时通常不推荐使用ZeroPadding,因为ECB模式下每个密文块都是独立加密的,相同的明文会得到相同的密文,这可能导致安全问题。但如果你坚持要使用,下面是一个简单的示例展示了如何实现AES ECB模式的ZeroPadding: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AES_ECB_ZeroPadding { private static final String ALGORITHM = "AES"; private static final String KEY = "your_secret_key"; // 替换为你自己的秘钥 public static void main(String[] args) throws Exception { byte[] keyBytes = Base64.getDecoder().decode(KEY); SecretKeySpec secretKey = new SecretKeySpec(keyBytes, ALGORITHM); // 创建Cipher实例并设置模式为ECB Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKey); String plainText = "Hello, World!"; // 明文 byte[] padding = pad(plainText.getBytes(), cipher.getBlockSize()); // ZeroPadding byte[] encrypted = cipher.doFinal(padding); // 加密 System.out.println("Encrypted text: " + Base64.getEncoder().encodeToString(encrypted)); } // ZeroPadding函数 private static byte[] pad(byte[] input, int blockSize) { int paddingLength = blockSize - (input.length % blockSize); byte[] paddedInput = new byte[input.length + paddingLength]; System.arraycopy(input, 0, paddedInput, 0, input.length); for (int i = 0; i < paddingLength; i++) { paddedInput[input.length + i] = (byte) paddingLength; } return paddedInput; } } ``` 请注意,实际生产环境中使用ECB模式加密并不常见,因为它缺乏保密性。推荐使用CBC模式或其他更强的模式,如CBC+PKCS#7 Padding。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值