您的位置 首页 java

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 = Base64.encodeBase64String(key.getEncoded());

return keyStr;

}

//根据password生成密钥串

static String genKeyAES(String password) throws Exception {

SecretKey key = genRawKeyAES(password);

String keyStr = Base64.encodeBase64String(key.getEncoded());

return keyStr;

}

//根据password生成原始密钥串

static SecretKey genRawKeyAES(String password) throws Exception {

KeyGenerator keyGen = KeyGenerator.getInstance(“AES”);

keyGen.init(128,new SecureRandom(password.getBytes(“utf8”)));

SecretKey key = keyGen.generateKey();

return key;

}

//根据密钥串获取密钥

static SecretKey loadKeyAES(String keyStr) throws Exception {

SecretKey key = new SecretKeySpec(Base64.decodeBase64(keyStr), “AES”);

return key;

}

//AES加密

static String encryptAES(String source, SecretKey key) throws Exception {

Cipher cipher = Cipher.getInstance(“AES”);

cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] result = cipher.doFinal(source.getBytes(“utf8”));

return Base64.encodeBase64String(result);

}

//AES解密

static String deencryptAES(String source, SecretKey key) throws Exception {

Cipher cipher = Cipher.getInstance(“AES”);

cipher.init(Cipher.DECRYPT_MODE, key);

byte[] resultByte = cipher.doFinal(Base64.decodeBase64(source));

String result = new String(resultByte,”utf-8″);

return result;

}

}

运行结果:

message source : study hard and make progress everyday

AES keyStr : evD5UdP8LK8UrfrmxGQheA==

AES encrypt result : 1z8zSWmRRFPNb6qoURgFp1c778SzaDqbErrVroDthM5eBXrQTFevAzYmRStK7EPZ

AES deencrypt result : study hard and make progress everyday

3.3 非对称加密算法RSA代码实例

public class RSAMain {

public static void main(String[] args) throws Exception {

String source = “study hard and make progress everyday”;

System.out.println(“message source : “+source);

KeyPair keyPair = getKeyPair(); //生成密钥对

String pubKeyStr = getPubKey(keyPair); //获取公钥串

System.out.println(“pubKeyStr : “+pubKeyStr);

String priKeyStr = getPriKey(keyPair); //获取私钥串

System.out.println(“priKeyStr : “+priKeyStr);

PublicKey pubKey = loadPubKey(pubKeyStr);//加载公钥

PrivateKey priKey = loadPriKey(priKeyStr);//加载私钥

/**************** 公钥加密 私钥解密********************/

System.out.println(“\n/**************** 公钥加密 私钥解密********************/”);

String encryptStr = pubEncrypt(source,pubKey); //RSA加密

System.out.println(“RSA pubKey encrypt result : ” + encryptStr);

String decryptStr = priDecrypt(encryptStr,priKey); //RSA解密

System.out.println(“RSA priKey decryptStr result : ” +decryptStr);

/**************** 私钥加密 公钥解密********************/

System.out.println(“\n/**************** 私钥加密 公钥解密********************/”);

encryptStr = priEncrypt(source,priKey); //RSA加密

System.out.println(“RSA priKey encrypt result : ” + encryptStr);

decryptStr = pubDecrypt(encryptStr,pubKey); //RSA解密

System.out.println(“RSA pubKey decryptStr result : ” +decryptStr);

}

//生成密钥对

static KeyPair getKeyPair() throws Exception {

KeyPairGenerator keyGen = KeyPairGenerator.getInstance(“RSA”);

keyGen.initialize(512); //可以理解为:加密后的密文长度,实际原文要小些 越大 加密解密越慢

KeyPair keyPair = keyGen.generateKeyPair();

return keyPair;

}

//获取公钥Base64字符串

static String getPubKey(KeyPair keyPair){

PublicKey key = keyPair.getPublic();

return Base64.encodeBase64String(key.getEncoded());

}

//获取私钥Base64字符串

static String getPriKey(KeyPair keyPair){

PrivateKey key = keyPair.getPrivate();

return Base64.encodeBase64String(key.getEncoded());

}

//根据公钥串获取公钥

static PublicKey loadPubKey(String keyStr) throws Exception {

X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(keyStr));

KeyFactory keyFactory = KeyFactory.getInstance(“RSA”);

PublicKey key = keyFactory.generatePublic(keySpec);

return key;

}

//根据私钥串获取私钥

static PrivateKey loadPriKey(String keyStr) throws Exception {

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(keyStr));

KeyFactory keyFactory = KeyFactory.getInstance(“RSA”);

PrivateKey key = keyFactory.generatePrivate(keySpec);

return key;

}

/**************** 公钥加密 私钥解密********************/

//使用公钥加密

static String pubEncrypt(String source,PublicKey key) throws Exception {

Cipher cipher = Cipher.getInstance(“RSA”);

cipher.init(Cipher.ENCRYPT_MODE,key);

return Base64.encodeBase64String(cipher.doFinal(source.getBytes(“utf8”)));

}

//使用私钥解密

static String priDecrypt(String source,PrivateKey key) throws Exception {

Cipher cipher = Cipher.getInstance(“RSA”);

cipher.init(Cipher.DECRYPT_MODE,key);

return new String(cipher.doFinal(Base64.decodeBase64(source)),”utf8″);

}

/**************** 私钥加密 公钥解密********************/

//使用私钥加密

static String priEncrypt(String source,PrivateKey key) throws Exception {

Cipher cipher = Cipher.getInstance(“RSA”);

cipher.init(Cipher.ENCRYPT_MODE,key);

return Base64.encodeBase64String(cipher.doFinal(source.getBytes(“utf8”)));

}

//使用公钥解密

static String pubDecrypt(String source,PublicKey key) throws Exception {

Cipher cipher = Cipher.getInstance(“RSA”);

cipher.init(Cipher.DECRYPT_MODE,key);

return new String(cipher.doFinal(Base64.decodeBase64(source)),”utf8″);

}

}

运行结果:

message source : study hard and make progress everyday

pubKeyStr : M2wwDQYJKoZIhvcNAQEBBQADSwAwSAJBAItWYa39aUhRTIXEIBCSfSCp9CvXj/k9STtMv7y5OVD9ILArIf8ZwU+qepahkO40EUJ37IBS3ciiTw7CcS7U7UsCAwEAAQ==

priKeyStr : M2IBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAi1Zhrf1pSFFMhcQgEJJ9IKn0K9eP+T1JO0y/vLk5UP0gsCsh/xnBT6p6lqGQ7jQRQnfsgFLdyKJPDsJxLtTtSwIDAQABAkBeSJNMIl9tWeXH1hBEZntY8OeSCwkXA8tb3vEXCNap37p06hj5d2gqaK/ZkgBqVfY6keCcRqbkOROyxdfCQTjBAiEA49WvON+HhlApKXHhHglz9bmpu+LLp6NGDicTLszfGLECIQCckAMKaWcn8u1V+svGbIBHxiKI+QUBXbbo6sUZt/UkuwIgEDpcLLTfNlXnWKhf3H/X3pzG1jclQl+C0ec+morFKUECIE5CMjLnIvg2FuqOdYOWwrydzq93Akh/hqmAiMtlR7V3AiBVblFmuDimgKb8OWg+2BaWTuKZA/BG9Z8nsT2tqaNuSA==

/**************** 公钥加密 私钥解密********************/

RSA pubKey encrypt result : do1DUKBnm9J49+IhFDqPEI53tGX69kPfPbqYsPPEabm9NYTvNiEEUzjT5w1j1yQtxlz7T2n6QyHKHv0BjZOoqg==

RSA priKey decryptStr result : study hard and make progress everyday

/**************** 私钥加密 公钥解密********************/

RSA priKey encrypt result : S6bEfnsciTRNmdqe3mh9LBUsyYS5Qff6nj2xRxaiyhi2/Frw17snIZfB0rOTSnu7JjamjLZozaJ/WlwdEFcloA==

RSA pubKey decryptStr result : study hard and make progress everyday

文章来源:智云一二三科技

文章标题:java中加密算法AES和RSA

文章地址:https://www.zhihuclub.com/184764.shtml

关于作者: 智云科技

热门文章

网站地图