AESCCMjava代码
⽹络上很多AES加密⽅式,前不久玩着⽆聊向玩玩CCM加密解密,却发现百度和⾕歌对于CCM的java加密解密代码太少了,今天刚刚琢磨出CCM的加密解密代码,不要问我细致的东西,俺只是研究前辈们的思路⾃⼰琢磨出的⽅式,废话不多说了,上代码。
pto.Cipher;
pto.spec.GCMParameterSpec;
pto.spec.SecretKeySpec;
l.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 = Instance("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()));*/
}
}
java源代码加密上⾯是加密的代码,代码要求:1.jdk版本⼤于等于1.8 2.需要事先导⼊⼀个bcprov.jar⽂件
上⾯代码加密后的数据为16字节密⽂加上4字节的mic
2A19DD67D1BE37892A2913A365BA22B886B8F5BA
然后我们再说解密的。
解密部分⼤家都知道需要密⽂,CCM也需要⼀个MIC,当初考虑到源码中⽤到cipher的updateAAD(byte[] byte)⽅法,但每次失败,尝试使⽤16字节的密⽂加上4字节mic⼀起传⼊cipher中
import pto.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 = Instance("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
好了 ,代码模仿⾕歌前辈琢磨写的,⼤神勿喷
其中的Security.addProvider(new BouncyCastleProvider());操作需要导⼊⼀个jar⽂件,
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论