import javax.crypto.Cipher;
import java.io.InputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
*@Author 黃俊聰
*@Date 2017/12/15 17:29
*@Description 非對稱加密解密工具類
*/
public class RSAUtil {
/**
* 私鑰字元串
*/
private static String PRIVATE_KEY ="";
/**
* 公鑰字元串
*/
private static String PUBLIC_KEY ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbpmF28RgRDMduGSDhB2CD 0CiOFYytTGxYQuffq5RTgdoxxsE/3dgE+qQaDsTG1yzOwwCq7X3Xye7MZlcL 5SjNiLzh5tSEG7qyAVUfAgit1gYczWM+sTg+G7pnHa/omukvOfEeWceS8P35 Xt3ShqIeKfGxU4UIdiqKonBrQtYT/wIDAQAB";
public static final String KEY_ALGORITHM = "RSA";
/**
* 讀取密鑰字元串
* @throws Exception
*/
public static void convert() throws Exception {
byte[] data = null;
try {
InputStream is = RSAUtil.class.getResourceAsStream("/enc_pri");
int length = is.available();
data = new byte[length];
is.read(data);
} catch (Exception e) {
}
String dataStr = new String(data);
try {
PRIVATE_KEY = dataStr;
} catch (Exception e) {
}
if (PRIVATE_KEY == null) {
throw new Exception("Fail to retrieve key");
}
}
/**
*@Author 黃俊聰
*@Date 2017/12/15 18:09
*@Description RSA私鑰解密
*/
public static byte[] decryptByPrivateKey(byte[] data) throws Exception {
//從流中讀取密鑰字元串
convert();
//base64解碼
byte[] keyBytes = Base64Util.decode(PRIVATE_KEY);
//用PKCS8EncodedKeySpec這種模式解密
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
//選用RSA非對稱算法進行解密
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//擷取私鑰
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
//用RSA算法擷取Cipher
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//初始化解密模式
cipher.init(Cipher.DECRYPT_MODE,privateKey);
return cipher.doFinal(data);
}
/**
*@Author 黃俊聰
*@Date 2017/12/15 18:18
*@Description RSA公鑰加密
*/
public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
//base64解碼
byte[] keyBytes = Base64Util.decode(key);
//用X509EncodedKeySpec這種模式加密
X509EncodedKeySpec pkcs8KeySpec = new X509EncodedKeySpec(keyBytes);
//選用RSA非對稱算法進行加密
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//擷取公鑰
Key publicKey = keyFactory.generatePublic(pkcs8KeySpec);
//用RSA算法擷取Cipher
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//初始化加密模式
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
public static void main(String[] args) throws Exception {
// //根據RSA生成一對key,即公鑰和私鑰
// KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
// //設定key的大小,1024K
// keyPairGenerator.initialize(1024);
// //擷取key對的對象
// KeyPair keyPair = keyPairGenerator.generateKeyPair();
// //擷取私鑰
// PrivateKey privateKey = keyPair.getPrivate();
// //擷取公鑰
// PublicKey publicKey = keyPair.getPublic();
// System.out.println(Base64Util.encode(publicKey.getEncoded()));
// System.out.println(Base64Util.encode(privateKey.getEncoded()));
String data = "黃俊聰來了";
byte[] enResult = encryptByPublicKey(data.getBytes("UTF-8"), PUBLIC_KEY);
System.out.println(enResult.toString());
byte[] deResult = decryptByPrivateKey(enResult);
System.out.println(new String(deResult,"UTF-8"));
}
//Base64工具類
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Base64Util {
private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.toCharArray();
public static String encode(byte[] data) {
byte start = 0;
int len = data.length;
StringBuffer buf = new StringBuffer(data.length * 3 / 2);
int end = len - 3;
int i = start;
int n = 0;
int d;
while (i <= end) {
d = (data[i] & 255) << 16 | (data[i + 1] & 255) << 8 | data[i + 2] & 255;
buf.append(legalChars[d >> 18 & 63]);
buf.append(legalChars[d >> 12 & 63]);
buf.append(legalChars[d >> 6 & 63]);
buf.append(legalChars[d & 63]);
i += 3;
if (n++ >= 14) {
n = 0;
buf.append(" ");
}
}
if (i == start + len - 2) {
d = (data[i] & 255) << 16 | (data[i + 1] & 255) << 8;
buf.append(legalChars[d >> 18 & 63]);
buf.append(legalChars[d >> 12 & 63]);
buf.append(legalChars[d >> 6 & 63]);
buf.append("=");
} else if (i == start + len - 1) {
d = (data[i] & 255) << 16;
buf.append(legalChars[d >> 18 & 63]);
buf.append(legalChars[d >> 12 & 63]);
buf.append("==");
}
return buf.toString();
}
private static int decode(char c) {
if (c >= 65 && c <= 90) {
return c - 65;
} else if (c >= 97 && c <= 122) {
return c - 97 + 26;
} else if (c >= 48 && c <= 57) {
return c - 48 + 26 + 26;
} else {
switch (c) {
case '+':
return 62;
case '/':
return 63;
case '=':
return 0;
default:
throw new RuntimeException("unexpected code: " + c);
}
}
}
public static byte[] decode(String s) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
decode(s, bos);
} catch (IOException var5) {
throw new RuntimeException();
}
byte[] decodedBytes = bos.toByteArray();
try {
bos.close();
bos = null;
} catch (IOException var4) {
System.err.println("Error while decoding BASE64: " + var4.toString());
}
return decodedBytes;
}
private static void decode(String s, OutputStream os) throws IOException {
int i = 0;
int len = s.length();
while (true) {
while (i < len && s.charAt(i) <= 32) {
++i;
}
if (i == len) {
break;
}
int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6)
+ decode(s.charAt(i + 3));
os.write(tri >> 16 & 255);
if (s.charAt(i + 2) == 61) {
break;
}
os.write(tri >> 8 & 255);
if (s.charAt(i + 3) == 61) {
break;
}
os.write(tri & 255);
i += 4;
}
}
}