AES和RSA加密演算法入門Demo
阿新 • • 發佈:2019-01-02
首先感謝博主開園精神,此部落格是個人結合博主博文來進行一次個人的總結,加深學習印象。博主已經總結的非常的不錯,大家可以參考博主原文博主部落格地址
資料參考:
博主原始碼下載
百度百科
Java中有對稱加密和非對稱加密。
對稱加密演算法在加密和解密時使用的是同一個祕鑰;而非對稱加密演算法需要兩個金鑰來進行加密和解密,這兩個祕鑰是公開金鑰(public key,簡稱公鑰)和私有金鑰(private key,簡稱私鑰),要麼公鑰加密私鑰加密,要麼私鑰加密公鑰揭祕。
下面來學習AES(對稱加密)和RAS(非對稱加密)
AES(高階加密標準)
高階加密標準(英語:Advanced Encryption Standard,縮寫:AES),在密碼學中又稱Rijndael加密法,是美國聯邦政府採用的一種區塊加密標準。這個標準用來替代原先的DES,已經被多方分析且廣為全世界所使用。經過五年的甄選流程,高階加密標準由美國國家標準與技術研究院(NIST)於2001年11月26日釋出於FIPS PUB 197,並在2002年5月26日成為有效的標準。2006年,高階加密標準已然成為對稱金鑰加密中最流行的演算法之一。
RAS
之所以叫 RSA演算法,是因為演算法的三位發明者RSA是目前最有影響力的公鑰加密演算法
下面提出demo,具體講解大家參考博主原文。
客戶端程式碼:
package base64;
public class Client {
public static void main(String[] args){
// rsaTest();
// aesTest();
rse_aesTest();
}
/**
* 模擬RSA公鑰加密
* 生成的公鑰就是解密需要獲取的引數
*/
private static void rsaTest(){
try {
String encryptText=RSAUtils.encryptByPublicKey("Beyond黃家駒" );
System.out.println("公鑰:"+encryptText);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 模擬AES加密
* 解密需要key和encryptText
*/
private static void aesTest(){
//明文
String content="AES加密演算法";
//金鑰
String key=AESUtils.generateKey();
//密文
String encryptText=AESUtils.encryptData(key,content);
System.out.println("key:"+key);
System.out.println("金鑰:"+encryptText);
}
/**
* RSA和AES結合使用
*/
private static void rse_aesTest(){
String text="我是要加密的資訊";
//使用AES對資訊加密
String key=AESUtils.generateKey();
String encryptText=AESUtils.encryptData(key,text);
//使用RSA對AES的金鑰加密
try {
String doubleKey=RSAUtils.encryptByPublicKey(key);
String doubleencryptText=RSAUtils.encryptByPublicKey(encryptText);
System.out.println("要傳到服務端的密文:"+doubleencryptText);
System.out.println("要傳到服務端的金鑰:"+doubleKey);
} catch (Exception e) {
e.printStackTrace();
}
}
}
服務端程式碼:
package base64;
public class Server {
public static void main(String[] args) {
// rsaTest();
// aesTest();
rsa_aesTest();
}
/**
* 解密需要的引數是客戶端加密的公鑰
*/
private static void rsaTest() {
String encryptText = "QclhVvuJJJTd/2KVotzKlTYJEDZh1x1w5KThxyttQZZVGaapyHyEpEprkjHwBlb9xpfHefTIqPscMDXlkuO+yyi09Na0PjLBMl7a8iyVM8MLMedzeU+dgSmAi629u73ZnrOBvs1Oq" +
"UJswh2P9kqysKSN7MXL2t56KUn93iwY7I0=";
try {
String text = RSAUtils.decryptByPrivateKey(encryptText);
System.out.println("明文:" + text);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void aesTest() {
/**
* 每一個key對應一個encryptText,只要key相同那麼每一個文字生成的encryptText都是唯一的
*/
String encryptText = "r2aEHW20cXZ9+NGNklHDwQ==";
String key="8f9046aac19c45d0";
try {
String text = AESUtils.decryptData(key,encryptText);
System.out.println("明文:" + text);
} catch (Exception e) {e.printStackTrace();
}
}
private static void rsa_aesTest(){
//客戶端發來的密文
String doubleEnCryptText="UUAYnThYdXR58mJU9wV9crWf5vmODCDVUF0iu8CmM0Q2etKABgJfnZg1gCqV1bP5kv5IEV33TEgNM3CuoF5Ick+VI02wwJITioAfWK5cB6GB7W8SLvwZCKfRyxa" +
"cLLKbgUtCB2AZA8BblOqZbkc8E+tY9QpausMePtzOoX4gs3w=";
//客戶端發來的金鑰
String doubleKey="LY8PY7htpWM5W2XtU58sQyE84qur1JVpOJ0zO2++Y5LSj41mrwv9JUA5611kIvXuWTDdkOXukdk1b8fbZWfmwdmlCEAOvAJ2lmo7Hwb7rfEILSzXkXnHxlxWuCkXsgZOqnK2eGVs" +
"vFTEPqzci77vHCMyTXoGLFTPNV09AyqQgyo=";
try {
//RSA解密
String key=RSAUtils.decryptByPrivateKey(doubleKey);
String encrtptText=RSAUtils.decryptByPrivateKey(doubleEnCryptText);
//AES解密
String text=AESUtils.decryptData(key,encrtptText);
//解密完成的明文
System.out.println("明文:"+text);
} catch (Exception e) {
e.printStackTrace();
}
}
}
加密解密演算法工具類
AESUtils.java
package base64;
import java.util.UUID;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* AES工具類,金鑰必須是16位字串
*/
public class AESUtils {
/**偏移量,必須是16位字串*/
private static final String IV_STRING = "16-Bytes--String";
/**
* 預設的金鑰
*/
public static final String DEFAULT_KEY = "1bd83b249a414036";
/**
* 產生隨機金鑰(這裡產生金鑰必須是16位)
*/
public static String generateKey() {
String key = UUID.randomUUID().toString();
key = key.replace("-", "").substring(0, 16);// 替換掉-號
return key;
}
public static String encryptData(String key, String content) {
byte[] encryptedBytes = new byte[0];
try {
byte[] byteContent = content.getBytes("UTF-8");
// 注意,為了能與 iOS 統一
// 這裡的 key 不可以使用 KeyGenerator、SecureRandom、SecretKey 生成
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
// 指定加密的演算法、工作模式和填充方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
encryptedBytes = cipher.doFinal(byteContent);
// 同樣對加密後資料進行 base64 編碼
return Base64Utils.encode(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decryptData(String key, String content) {
try {
// base64 解碼
byte[] encryptedBytes = Base64Utils.decode(content);
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] result = cipher.doFinal(encryptedBytes);
return new String(result, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String plainText = AESUtils.decryptData("F431E6FF9051DA07", "q8jHYk6LSbwC2K4zmr/wRZo8mlH0VdMzPEcAzQadTCpSrPQ/ZnTmuIvQxiLOnUXu");
System.out.println("aes加密後: " + plainText);
}
}
RSAUtils.java
package base64;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class RSAUtils {
public static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJFBnk78A4CN5gBpIV/pGOGqi/CzvwjvXoj2gYXtbEIg+ZxpRrVi7Is6dwIK4+xrDr35ExaN1s4GnyF3g88z93iYpM5URhQTRJ/GGENNlozkLNARRdTJfLuJxBMZHnAGOtuNTXIcIo5/k8klllBYHTqG6xIVnjRN0vsV2UGlnW7VAgMBAAECgYBMoT9xD8aRNUrXgJ7YyFIWCzEUZN8tSYqn2tPt4ZkxMdA9UdS5sFx1/vv1meUwPjJiylnlliJyQlAFCdYBo7qzmib8+3Q8EU3MDP9bNlpxxC1go57/q/TbaymWyOk3pK2VXaX+8vQmllgRZMQRi2JFBHVoep1f1x7lSsf2TpipgQJBANJlO+UDmync9X/1YdrVaDOi4o7g3w9u1eVq9B01+WklAP3bvxIoBRI97HlDPKHx+CZXeODx1xj0xPOK3HUz5FECQQCwvdagPPtWHhHx0boPF/s4ZrTUIH04afuePUuwKTQQRijnl0eb2idBe0z2VAH1utPps/p4SpuT3HI3PJJ8MlVFAkAFypuXdj3zLQ3k89A5wd4Ybcdmv3HkbtyccBFALJgs+MPKOR5NVaSuF95GiD9HBe4awBWnu4B8Q2CYg54F6+PBAkBKNgvukGyARnQGc6eKOumTTxzSjSnHDElIsjgbqdFgm/UE+TJqMHmXNyyjqbaA9YeRc67R35HfzgpvQxHG8GN5AkEAxSKOlfACUCQ/CZJovETMmaUDas463hbrUznp71uRMk8RP7DY/lBnGGMeUeeZLIVK5X2Ngcp9nJQSKWCGtpnfLQ==";
private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRQZ5O/AOAjeYAaSFf6Rjhqovws78I716I9oGF7WxCIPmcaUa1YuyLOncCCuPsaw69+RMWjdbOBp8hd4PPM/d4mKTOVEYUE0SfxhhDTZaM5CzQEUXUyXy7icQTGR5wBjrbjU1yHCKOf5PJJZZQWB06husSFZ40TdL7FdlBpZ1u1QIDAQAB";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* 加密演算法RSA
*/
private static final String KEY_ALGORITHM = "RSA";
/**
* 生成公鑰和私鑰
*
* @throws Exception
*/
public static void getKeys() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyStr = getPublicKeyStr(publicKey);
String privateKeyStr = getPrivateKeyStr(privateKey);
System.out.println("公鑰\r\n" + publicKeyStr);
System.out.println("私鑰\r\n" + privateKeyStr);
}
/**
* 使用模和指數生成RSA公鑰
* 注意:【此程式碼用了預設補位方式,為RSA/None/PKCS1Padding,不同JDK預設的補位方式可能不同,如Android預設是RSA
* /None/NoPadding】
*
* @param modulus 模
* @param exponent 公鑰指數
* @return
*/
public static RSAPublicKey getPublicKey(String modulus, String exponent) {
try {
BigInteger b1 = new BigInteger(modulus);
BigInteger b2 = new BigInteger(exponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 使用模和指數生成RSA私鑰
* 注意:【此程式碼用了預設補位方式,為RSA/None/PKCS1Padding,不同JDK預設的補位方式可能不同,如Android預設是RSA
* /None/NoPadding】
*
* @param modulus 模
* @param exponent 指數
* @return
*/
public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
try {
BigInteger b1 = new BigInteger(modulus);
BigInteger b2 = new BigInteger(exponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 公鑰加密
*
* @param data
* @return
* @throws Exception
*/
public static String encryptByPublicKey(String data) throws Exception {
byte[] dataByte = data.getBytes();
byte[] keyBytes = Base64Utils.decode(PUBLIC_KEY);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 對資料加密
// Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = dataByte.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對資料分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(dataByte, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(dataByte, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return Base64Utils.encode(encryptedData);
}
/**
* 私鑰解密
*
* @param data
* @return
* @throws Exception
*/
public static String decryptByPrivateKey(String data) throws Exception {
byte[] encryptedData = Base64Utils.decode(data);
byte[] keyBytes = Base64Utils.decode(PRIVATE_KEY);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對資料分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher
.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher
.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return new String(decryptedData);
}
/**
* 獲取模數和金鑰
*
* @return
*/
public static Map<String, String> getModulusAndKeys() {
Map<String, String> map = new HashMap<String, String>();
try {
InputStream in = RSAUtils.class
.getResourceAsStream("/rsa.properties");
Properties prop = new Properties();
prop.load(in);
String modulus = prop.getProperty("modulus");
String publicKey = prop.getProperty("publicKey");
String privateKey = prop.getProperty("privateKey");
in.close();
map.put("modulus", modulus);
map.put("publicKey", publicKey);
map.put("privateKey", privateKey);
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
/**
* 從字串中載入公鑰
*
* @param publicKeyStr 公鑰資料字串
* @throws Exception 載入公鑰時產生的異常
*/
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
try {
byte[] buffer = Base64Utils.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此演算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公鑰非法");
} catch (NullPointerException e) {
throw new Exception("公鑰資料為空");
}
}
/**
* 從字串中載入私鑰<br>
* 載入時使用的是PKCS8EncodedKeySpec(PKCS#8編碼的Key指令)。
*
* @param privateKeyStr
* @return
* @throws Exception
*/
public static PrivateKey loadPrivateKey(String privateKeyStr)
throws Exception {
try {
byte[] buffer = Base64Utils.decode(privateKeyStr);
// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此演算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私鑰非法");
} catch (NullPointerException e) {
throw new Exception("私鑰資料為空");
}
}
public static String getPrivateKeyStr(PrivateKey privateKey)
throws Exception {
return new String(Base64Utils.encode(privateKey.getEncoded()));
}
public static String getPublicKeyStr(PublicKey publicKey) throws Exception {
return new String(Base64Utils.encode(publicKey.getEncoded()));
}
public static void main(String[] args) throws Exception {
getKeys();
}
}
Base64Utils.java
package base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import it.sauronsoftware.base64.Base64;
/** */
/**
* <p>
* BASE64編碼解碼工具包
* </p>
* <p>
* 依賴javabase64-1.3.1.jar
* </p>
*
* @author jun
* @date 2012-5-19
* @version 1.0
*/
public class Base64Utils {
/** */
/**
* 檔案讀取緩衝區大小
*/
private static final int CACHE_SIZE = 1024;
/** */
/**
* <p>
* BASE64字串解碼為二進位制資料
* </p>
*
* @param base64
* @return
* @throws Exception
*/
public static byte[] decode(String base64) throws Exception {
return Base64.decode(base64.getBytes());
}
public static String decode(byte[] b) {
return new String(Base64.decode(b));
}
/** */
/**
* <p>
* 二進位制資料編碼為BASE64字串
* </p>
*
* @param bytes
* @return
* @throws Exception
*/
public static String encode(byte[] bytes) throws Exception {
return new String(Base64.encode(bytes));
}
/** */
/**
* <p>
* 將檔案編碼為BASE64字串
* </p>
* <p>
* 大檔案慎用,可能會導致記憶體溢位
* </p>
*
* @param filePath
* 檔案絕對路徑
* @return
* @throws Exception
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
}
/** */
/**
* <p>
* BASE64字串轉回檔案
* </p>
*
* @param filePath
* 檔案絕對路徑
* @param base64
* 編碼字串
* @throws Exception
*/
public static void decodeToFile(String filePath, String base64)
throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
}
/** */
/**
* <p>
* 檔案轉換為二進位制陣列
* </p>
*
* @param filePath
* 檔案路徑
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
/** */
/**
* <p>
* 二進位制資料寫檔案
* </p>
*
* @param bytes
* 二進位制資料
* @param filePath
* 檔案生成目錄
*/
public static void byteArrayToFile(byte[] bytes, String filePath)
throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
}
}