AES CCM java代码

来源:互联网 发布:淘宝自动回复内容 编辑:程序博客网 时间:2024/05/17 02:58

网络上很多AES加密方式,前不久玩着无聊向玩玩CCM加密解密,却发现百度和谷歌对于CCM的java加密解密代码太少了,今天刚刚琢磨出CCM的加密解密代码,不要问我细致的东西,俺只是研究前辈们的思路自己琢磨出的方式,废话不多说了,上代码。



import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;


import org.bouncycastle.jce.provider.BouncyCastleProvider;


import java.security.Security;
public class Main {

static byte[] testInput = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'};
static byte[] keyBytes = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,
0x09,0x10,0x11,0x12,0x13,0x14,0x15,0x16};
static byte[] nonce = {'a','b','c','d','e','f','g','h','i','j','k','l'};
    public static void main(String[] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        //32   mac 4字节  32位
        GCMParameterSpec parameterSpec = new GCMParameterSpec(32, nonce);
        Cipher cipher = Cipher.getInstance("AES/CCM/NoPadding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, parameterSpec);
        
        System.out.println(DatatypeConverter.printHexBinary(cipher.doFinal(testInput)));
        //下面的方式和上面的结果一样cipher.doFinal(testInput)--cipher.update(testInput);cipher.doFinal()
        /*cipher.update(testInput);
        System.out.println(DatatypeConverter.printHexBinary(cipher.doFinal()));*/
    }
}
上面是加密的代码,代码要求:1.jdk版本大于等于1.8  2.需要事先导入一个bcprov.jar文件

上面代码加密后的数据为16字节密文加上4字节的mic

2A19DD67D1BE37892A2913A365BA22B886B8F5BA

然后我们再说解密的。

解密部分大家都知道需要密文,CCM也需要一个MIC,当初考虑到源码中用到cipher的updateAAD(byte[] byte)方法,但每次失败,尝试使用16字节的密文加上4字节mic一起传入cipher中

import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.jce.provider.BouncyCastleProvider;


import java.security.Security;
public class Main {
static byte[] keyBytes = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,
0x09,0x10,0x11,0x12,0x13,0x14,0x15,0x16};
static byte[] nonce = {'a','b','c','d','e','f','g','h','i','j','k','l'};
    public static void main(String[] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        //32   mac 4字节  32位
        GCMParameterSpec parameterSpec = new GCMParameterSpec(32, nonce);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        Cipher cipherde = Cipher.getInstance("AES/CCM/NoPadding");
        cipherde.init(Cipher.DECRYPT_MODE, secretKeySpec, parameterSpec);
        byte[] decContext = {0x2A,0x19,(byte) 0xDD,0x67,(byte) 0xD1,(byte) 0xBE,0x37,(byte) 0x89,0x2A,0x29,
        0x13,(byte) 0xA3,0x65,(byte) 0xBA,0x22,(byte) 0xB8,(byte) 0x86,(byte) 0xB8,(byte) 0xF5,(byte) 0xBA};
        System.out.println(DatatypeConverter.printHexBinary(cipherde.doFinal(decContext)));
    }
}

解密出来的数据:6162636465666768696A6B6C6D6E6F70

好了 ,代码模仿谷歌前辈琢磨写的,大神勿喷