java+aes+ras_使用java实现对称加密解密(AES),非对称加密解密(RSA)

importjava.security.Key;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.SecureRandom;importjavax.crypto.Cipher;importjavax.crypto.KeyGenerator;importjavax.crypto.SecretKey;importjavax.crypto.spec.SecretKeySpec;importjavax.xml.bind.annotation.adapters.HexBinaryAdapter;public classDigestTest{public static voidmain(String[] args){try{

AESEncodeTest();

RSAEncodeTest();

}catch(Exception e){

e.printStackTrace();

}

}/*** AES对称加密

*@throwsException*/

private static void AESEncodeTest() throwsException{

String content= "content";

String key= "key"; //可以将该key存入本地文件,相当于一个秘钥。这个秘钥是不会通过网络传播的。//加密

KeyGenerator kg = KeyGenerator.getInstance("AES");

kg.init(128, newSecureRandom(key.getBytes()));

SecretKey secretKey=kg.generateKey();byte[] enCodeFormat =secretKey.getEncoded();

SecretKeySpec keySpec= new SecretKeySpec(enCodeFormat, "AES");

Cipher enCipher= Cipher.getInstance("AES");

enCipher.init(Cipher.ENCRYPT_MODE, keySpec);byte[] result =enCipher.doFinal(content.getBytes());

System.out.println("AES加密后:" + newHexBinaryAdapter().marshal(result));//解密//keyGenerator可以重复使用,但是每次使用前都需要调用init方法

kg.init(128, newSecureRandom(key.getBytes()));

SecretKeySpec dekeySpec= new SecretKeySpec(kg.generateKey().getEncoded(),"AES");

Cipher deCipher= Cipher.getInstance("AES");

deCipher.init(Cipher.DECRYPT_MODE, dekeySpec);

System.out.println("AES解密后:" + newString(deCipher.doFinal(result)));

}/*** RSA非对称加密

* 接收方生成的publicKey公布给发送方,发送方使用该公有秘钥加密之后,发送给接收方,然后接收方使用私有秘钥解密

* 如果接收方需要返回消息给发送方,同样也可以接受发送方生成的公有key,使用它加密后发送给发送方*/

private static void RSAEncodeTest() throwsException{

String content= "content";

KeyPairGenerator keyPairGenerator= KeyPairGenerator.getInstance("RSA");

keyPairGenerator.initialize(1024, newSecureRandom());

KeyPair keyPair=keyPairGenerator.generateKeyPair();//这儿模拟接收方生成了公、私有key。这些key可以存到文件里,要使用的时候读取出来即可

Key privateKey =keyPair.getPrivate();

Key publicKey=keyPair.getPublic();//这儿模拟发送方已经获取了接收方给的publicKey,并且使用它来加密要发送的数据

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(cipher.ENCRYPT_MODE, publicKey);byte[] result =cipher.doFinal(content.getBytes());

System.out.println("RSA加密后:" + newHexBinaryAdapter().marshal(result));//这儿模拟接收方使用自己生成的私钥进行解密

Cipher deCipher = Cipher.getInstance("RSA");

deCipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] deResult =deCipher.doFinal(result);

System.out.println("RSA解密后:" + newString(deResult));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值