java中加密算法AES和RSA
文章目录
一、简介
对于机密信息,我们需要加密,这里介绍加密算法在java中的使用。
二、知识点
目前常用的加密算法有对称加密算法与非对称加密算法。
2.1 对称加密算法
在对称加密中,加密方与解密方都共用同一个密钥,也就是加密与解密的密钥是一样的。
特点:
-
通常它的算法公开,加解密速度快。现在常用的AES算法,即advanced encrytion standard,
-
密钥长度,目前可用的是128位。
-
加密的原文长度不限。
2.2 非对称加密
非对称加密,又称公开密钥加密,它有两个密钥,公钥(public key)和私钥(private key),它们是不同的。公钥与私钥是配对使用的,使用公钥加密时,只有对应的私钥才能解开;用私钥加密时,只有对应的公钥才能解开。
特点:
-
通常是接收方先生成一对密钥,即公钥和私钥,然后公钥公开,发送方用公开的公钥加密,密方传给接收方,然后接收方用私钥解密。
-
非对称加密没有对称加密速度快,常用的是RSA算法。
-
RSA通常加密原文较小的串,串越大,keyGen.initialize(n)的n值就相应增大,加密解密速度越慢;
三、实例
3.1 添加base64的maven依赖
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
3.2 对称加密AES代码实例
public class AESMain {
public static void main(String[] args) throws Exception {
String source = "study hard and make progress everyday";
System.out.println("message source : "+source);
/********** 密钥生成方式一: 自动生成密钥 **************/
String keyStr = genKeyAES(); //生成密钥串
System.out.println("AES keyStr : "+keyStr);
SecretKey key = loadKeyAES(keyStr); //根据密钥串获取密钥
// /********** 密钥生成方式二: 指定种子(或者可以说是密码)生成密钥 ***********/
// String password = "123456";
// SecretKey key = genRawKeyAES(password); //根据password获取密钥
// String keyStr = Base64.encodeBase64String(key.getEncoded()); //生成密钥串
// System.out.println("AES keyStr : "+keyStr);
//
String encryptStr = encryptAES(source,key); //AES加密
System.out.println("AES encrypt result : " + encryptStr);
String deencryptStr = deencryptAES(encryptStr,key); //AES解密
System.out.println("AES deencrypt result : " +deencryptStr);
}
//生成密钥串
static String genKeyAES() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey key = keyGen.generateKey();
String keyStr