Java AES加密

做360广告的对接需要对密码进行AES加密,下面是点睛平台文档的描述:
(AES模式为CBC,加密算法MCRYPT_RIJNDAEL_128)对MD5加密后的密码实现对称加密。秘钥是apiSecret 的前16位,向量是后16位,加密结果为64位数字和小写字母。

用Java实现AES需要依赖Java加密扩展(The Java Cryptography Extension,简称JCE)的支持——主要是在 javax
下面的一些包。根据描述需要使用的算法为“AES/CBC/NoPadding”,实现方案如下:

public static String encode1(String src, String secretKey, String initialVector)
    throws Exception {
    Key key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
    AlgorithmParameterSpec spec = new IvParameterSpec(initialVector.getBytes(StandardCharsets.UTF_8));
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
 
    cipher.init(Cipher.ENCRYPT_MODE, key, spec);
    byte[] encrypted = cipher.doFinal(src.getBytes());
    
    return Hex.encodeHexString(encrypted);
}

这里使用的

SecretKeySpec




AlgorithmParameterSpec




IvParameterSpec


等类都是JCE提供的,通常在JVM环境下可以直接使用。

Hex
.
encodeHexString
(
)


方法则是由 apache-commons-codec
提供的。如果不想多引入一个依赖也可以使用下面的方法:

public static String toHexString(byte[] bytes) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < bytes.length; i++) {
    String hex = Integer.toHexString(0xFF & bytes[i]);
    if (hex.length() < 2) {
        builder.append(0);
    }
    builder.append(hex);
    }
    return builder.toString();
}

下面是为这个加密方法写的单元测试:

@Test
public void encode1() throws Exception {
    String src = "098f6bcd4621d373cade4e832627b4f6";
    String key = "1234567891234567";
    String iv = "8912345678912345";
 
    String result = AES.encode1(src, key, iv);
    String expect = "21fa89586f4a299545307b99036a082e135b52d3f63f93541e4291669a0de1de";
    Assert.assertEquals(expect, result);
}

这里的代码大体上能够满足360广告的对接需求了。但是因为jdk11偶尔对一些javax扩展包的不支持,我有些不太喜欢这个方案。另外在一些资料中也了解到jdk对AES 256加密是有一些限制的,要响应相关限制需要引入一个授权文件或者更换jdk,这就有些难接受了。种种原因吧,我需要一个替换方案。

最开始我以为在 apache-common-codec
中会有相关方案,但是结果是让人失望的。不过还好,最终我找到了 Bouncy Castle
。以下是关于Bouncy Castle的一些描述:
Bouncy Castle 是一种用于Java平台的开放源码的轻量级密码算法包。它支持大量的密码算法,并提供 JCE 1.2.1 的实现。Bouncy Castle是轻量级的,从J2SE 1.4到J2ME(包括MIDP)平台,它都可以运行。它是在MIDP上运行的唯一完整的密码术包。

使用 Bouncy Castle
提供的能力必然需要先引入相关的依赖。针对不同的jdk版本,Bouncy Castle都有提供对应的Cryptography Provider。比如我使用的是JDK1.8,对应的就是 bcprov-jdk15to18
,相关的依赖如下:

    org.bouncycastle
    bcprov-jdk15to18
    1.66

基于Bouncy Castle实现的360点睛平台AES加密处理如下:

public static String encode2(String value, String secretKey, String initialVector) {
    try {
        BufferedBlockCipher cipher = getCipher(secretKey, initialVector);
        byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
        byte[] out = new byte[cipher.getOutputSize(bytes.length)];
        int len = cipher.processBytes(bytes, 0, bytes.length, out, 0);
        len += cipher.doFinal(out, len);
        byte[] arr = new byte[len];
        System.arraycopy(out, 0, arr, 0, len);
        return Hex.toHexString(arr);
    } catch (Exception e) {
        throw new EncryptException("Data encryption failed. " + e.getMessage());
    }
}
 
private static BufferedBlockCipher getCipher(String secretKey, String iniVector) {
    try {
        byte[] iv = iniVector.getBytes(StandardCharsets.UTF_8);
        CipherParameters params = new ParametersWithIV(new KeyParameter(secretKey.getBytes(StandardCharsets.UTF_8)), iv);
        BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        cipher.init(true, params);
        return cipher;
    } catch (Exception ex) {
        throw new EncryptException("Cannot intialize Bouncy Castle cipher. " + ex.getMessage());
    }
}

因为360点睛平台要求使用的加密key没有超过256位,所以两个方案都是行得通的。

我比较喜欢Bouncy Castle这个方案,这个方案相对较轻量,并且不依赖JCE。但是这个方案的不足之处也恰恰在于此:Java中的SSL层,JSSE和XML加密库都依赖到JCE,而且AES Key长度的校验是在

Cipher


类中进行的,在这些场景下Bouncy Castle也很难起到作用。

参考文档