java语言,如何实现AES加密(ZeroPadding)

public class AesUtils {

private static final String AES_MODE = "AES/ECB/NoPadding";
private static final int BLOCK_SIZE = 16;
private byte[] key=null;

private static byte[] generateKey() {
    //结尾0等同于C++字符串结尾的\0
    String strKey=“1234567890123450”;
    byte[] keyBytes = new byte[16];
    keyBytes  = strKey.getBytes(StandardCharsets.UTF-8);
    return keyBytes;
}

// ZeroPadding
private static byte[] zeroPad(byte[] data) {
    if (data.length % BLOCK_SIZE == 0) {
        return data;
    }
    int paddedLength = ((data.length + BLOCK_SIZE - 1) / BLOCK_SIZE) * BLOCK_SIZE;
    return Arrays.copyOf(data, paddedLength);
}

private static String delZero(byte[] decrypted) {
    int length = decrypted.length;
    while (length > 0 && decrypted[length - 1] == 0) {
        length--;
    }
    return new String(decrypted, 0, length, StandardCharsets.UTF_8);
}

public static String encrypt(String plainText) {
    try {
        byte[] key = generateKey();
        byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8);
        byte[] padded = zeroPad(plainBytes);

        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance(AES_MODE);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        
        byte[] encrypted = cipher.doFinal(padded);
        return Base64.getEncoder().encodeToString(encrypted);
    } catch (Exception e) {
        throw new RuntimeException("AES加密失败", e);
    }
}

public static String decrypt(String base64Cipher) {
    try {
        byte[] key = processKey("");
        byte[] encrypted = Base64.getDecoder().decode(base64Cipher);

        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance(AES_MODE);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        
        byte[] decrypted = cipher.doFinal(encrypted);
        return delZero(decrypted);
    } catch (Exception e) {
        throw new RuntimeException("AES解密失败", e);
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值