JAVA RSA非對稱分段加解密
阿新 • • 發佈:2018-12-22
我就不講原理了
直接開擼程式碼
祕鑰對生成,專案根目錄生成一個檔案。
也可直接取打印出來的私鑰和公鑰
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import sun.misc.BASE64Encoder;//jdk1.8報黃不影響使用
/**
* 指定加密演算法為RSA
*/
private static final String ALGORITHM = "RSA";
/**
* 金鑰長度,用來初始化
*/
private static final int KEYSIZE = 1024;
/**
* 指定公鑰存放檔案
*/
private static String PUBLIC_KEY_FILE = "PublicKey";
/**
* 指定私鑰存放檔案
*/
private static String PRIVATE_KEY_FILE = "PrivateKey";
public static void main(String[] args) throws Exception {
generateKeyPair();
}
/**
* 本系統生成金鑰對
*
* @throws Exception
*/
private static void generateKeyPair() throws Exception {
/** RSA演算法要求有一個可信任的隨機數源 */
/** 為RSA演算法建立一個KeyPairGenerator物件 */
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
/** 利用上面的隨機資料來源初始化這個KeyPairGenerator物件 */
keyPairGenerator.initialize(KEYSIZE);
/** 生成密匙對 */
KeyPair keyPair = keyPairGenerator.generateKeyPair();
/** 得到公鑰 */
Key publicKey = keyPair.getPublic();
/** 得到私鑰 */
Key privateKey = keyPair.getPrivate();
byte[] publicKeyBytes = publicKey.getEncoded();
byte[] privateKeyBytes = privateKey.getEncoded();
String publicKeyBase64 = new BASE64Encoder().encode(publicKeyBytes);
String privateKeyBase64 = new BASE64Encoder().encode(privateKeyBytes);
System.out.println("系統公鑰長度:" + publicKeyBase64.length());
System.out.println("系統公鑰:" + publicKeyBase64);
System.out.println("系統私鑰長度:" + privateKeyBase64.length());
System.out.println("系統私鑰:" + privateKeyBase64);
ObjectOutputStream oos1 = null;
ObjectOutputStream oos2 = null;
try {
/** 用物件流將生成的金鑰寫入檔案 */
oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
oos1.writeObject(publicKey);
oos2.writeObject(privateKey);
} catch (Exception e) {
throw e;
} finally {
/** 清空快取,關閉檔案輸出流 */
oos1.close();
oos2.close();
}
}
資料長度過長會報錯,這是需使用分段式加密
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.Key;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class RSAUtil {
/** 指定加密演算法為RSA */
private static final String ALGORITHM = "RSA";
/** 指定公鑰存放檔案 */
private static String PUBLIC_KEY_FILE = "PublicKey";
/** 指定私鑰存放檔案 */
private static String PRIVATE_KEY_FILE = "PrivateKey";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/** *//**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
//正常加密
public static String encryptOne(String source) throws Exception {
/** 獲得公鑰 */
Key publicKey = getKey(PUBLIC_KEY_FILE);
/** 得到Cipher物件來實現對源資料的RSA加密 */
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] b = source.getBytes();
/** 執行加密操作 */
byte[] b1 = cipher.doFinal(b);
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(b1);
}
//正常解密
public static String decrypt(String cryptograph) throws Exception {
Key privateKey = getKey(PRIVATE_KEY_FILE);
/** 得到Cipher物件對已用公鑰加密的資料進行RSA解密 */
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
BASE64Decoder decoder = new BASE64Decoder();
byte[] b1 = decoder.decodeBuffer(cryptograph);
/** 執行解密操作 */
byte[] b = cipher.doFinal(b1);
return new String(b);
}
//分段加密
public static byte[] encrypt(String source) throws Exception {
Key publicKey = getKey(PUBLIC_KEY_FILE);
/** 得到Cipher物件來實現對源資料的RSA加密 */
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] b = source.getBytes();
int inputLen = b.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( b, offSet, MAX_ENCRYPT_BLOCK);
}
else
{
cache = cipher.doFinal( b, offSet, inputLen - offSet);
}
out.write( cache, 0, cache. length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
//分段解密
public static String decryptByPrivateKey( byte[] encryptedData) throws Exception {
Key privateKey = getKey(PRIVATE_KEY_FILE);
Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
cipher.init(2, privateKey);
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);
}
private static Key getKey(String fileName) throws Exception, IOException {
Key key;
ObjectInputStream ois = null;
try {
/** 將檔案中的私鑰物件讀出 */
ois = new ObjectInputStream(new FileInputStream(fileName));
key = (Key) ois.readObject();
} catch (Exception e) {
throw e;
} finally {
ois.close();
}
return key;
}
}
問題一:spring boot專案需改下面配置
private static String PUBLIC_KEY_FILE = "PublicKey";
替換為:
private static String PUBLIC_KEY_FILE = "classpath:key/PublicKey.txt";
getKey(String fileName)方法內
ois = new ObjectInputStream(new FileInputStream(fileName));
替換為
ois = new ObjectInputStream(new FileInputStream(ResourceUtils.getFile(fileName)));
不替換本地跑是沒問題的,但是打包放到tomcat裡會找不到你的靜態檔案。
其他專案同理,只需替換靜態檔案路徑即可。
問題二:分段加密返回資料有特殊字元會被轉譯,暫時未解決。