public class RSACrypt {
/**
* 生成RAS公鑰與私鑰字符串,直接返回
*
* @return
*/
public static HashMap<String, String> getKeys() {
HashMap<String, String> map = new HashMap<String, String>();
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 初始化密鑰對生成器,密鑰大小為96-1024位
keyPairGen.initialize(1024, new SecureRandom());
// 生成一個密鑰對,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
// 得到公鑰字符串
String publicKey = base64ToStr(keyPair.getPublic().getEncoded());
// 得到私鑰字符串
String privateKey = base64ToStr(keyPair.getPrivate().getEncoded());
map.put("publicKey", publicKey);
map.put("privateKey", privateKey);
return map;
}
/**
* 根據公鑰字符串加載公鑰
*
* @param publicKeyStr 公鑰字符串
* @return
* @throws Exception
*/
public static RSAPublicKey loadPublicKey(String publicKeyStr) throws Exception {
try {
byte[] buffer = javax.xml.bind.DatatypeConverter.parseBase64Binary(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此算法", e);
} catch (InvalidKeySpecException e) {
throw new Exception("公鑰非法", e);
} catch (NullPointerException e) {
throw new Exception("公鑰數據為空", e);
}
}
/**
* 根據私鑰字符串加載私鑰
*
* @param privateKeyStr 私鑰字符串
* @return
* @throws Exception
*/
public static RSAPrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
try {
byte[] buffer = javax.xml.bind.DatatypeConverter.parseBase64Binary(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此算法", e);
} catch (InvalidKeySpecException e) {
throw new Exception("私鑰非法", e);
} catch (NullPointerException e) {
throw new Exception("私鑰數據為空", e);
}
}
/**
* 公鑰加密
*
* @param publicKey 公鑰
* @param plainTextData 明文數據
* @return
* @throws Exception 加密過程中的異常信息
*/
public static String encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
if (publicKey == null) {
throw new Exception("加密公鑰為空, 請設置");
}
Cipher cipher = null;
try {
// 使用默認RSA
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(plainTextData);
return base64ToStr(output);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此加密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("加密公鑰非法,請檢查");
} catch (IllegalBlockSizeException e) {
throw new Exception("明文長度非法");
} catch (BadPaddingException e) {
throw new Exception("明文數據已損壞");
}
}
public static String encrypt(byte[] plainTextData) throws Exception {
Cipher cipher = null;
try {
// 使用默認RSA
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, RSACrypt.loadPublicKey(pk));
byte[] output = cipher.doFinal(plainTextData);
return base64ToStr(output);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此加密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("加密公鑰非法,請檢查");
} catch (IllegalBlockSizeException e) {
throw new Exception("明文長度非法");
} catch (BadPaddingException e) {
throw new Exception("明文數據已損壞");
}
}
/**
* 私鑰解密
*
* @param privateKey 私鑰
* @param cipherData 密文數據
* @return 明文
* @throws Exception 解密過程中的異常信息
*/
public static String decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
if (privateKey == null) {
throw new Exception("解密私鑰為空, 請設置");
}
Cipher cipher = null;
try {
// 使用默認RSA
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(cipherData);
return new String(output);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此解密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("解密私鑰非法,請檢查");
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
throw new Exception("密文長度非法");
} catch (BadPaddingException e) {
e.printStackTrace();
throw new Exception("密文數據已損壞");
}
}
public static String decrypt(byte[] cipherData) throws Exception {
Cipher cipher = null;
try {
// 使用默認RSA
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, RSACrypt.loadPrivateKey(sk));
byte[] output = cipher.doFinal(cipherData);
return new String(output);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此解密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("解密私鑰非法,請檢查");
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
throw new Exception("密文長度非法");
} catch (BadPaddingException e) {
e.printStackTrace();
throw new Exception("密文數據已損壞");
}
}
public static String base64ToStr(byte[] b) {
return javax.xml.bind.DatatypeConverter.printBase64Binary(b);
}
public static byte[] strToBase64(String str) {
return javax.xml.bind.DatatypeConverter.parseBase64Binary(str);
}
}
生成秘鑰對,加密數據、解密數據
public static void main(String[] args) throws Exception {
//初始化階段,初始化后生成秘鑰對
//公鑰發送給消息發送方用於加密傳輸數據;私鑰嚴格保存於消息接收方,收到加密的消息之后進行解密
HashMap<String, String> map = RSACrypt.getKeys();
String privateKeyStr=map.get("privateKey");
String publicKeyStr=map.get("publicKey");
System.out.println("初始化私鑰為:"+privateKeyStr);
System.out.println("初始化共鑰為:"+publicKeyStr);
//消息發送方
String originData="你是收破爛的么?";
System.out.println("信息原文:"+originData);
String encryptData=RSACrypt.encrypt(RSACrypt.loadPublicKey(publicKeyStr),originData.getBytes());
System.out.println("加密后:"+encryptData);
//消息接收方
String decryptData=RSACrypt.decrypt(RSACrypt.loadPrivateKey(privateKeyStr),RSACrypt.strToBase64(encryptData));
System.out.println("解密后:"+decryptData);
}
結果輸出
初始化私鑰為:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAI2SyRvMxZTrlRx6oHav8lCECHX5wZ/pPkAsl1RIh/NMfV5wjN+3kGZrG6NEvI+xCuwwFGn8GwUDgqC6Hw5nA15chuRprZFDaXa9hFrC6r6jtQ6MPOsqdaDJSfpJIY64fZqoVLKdibV783mfL175n9IkaDuw3msumJyDOsgplIJ/AgMBAAECgYApC8rFBZyvbZIg3KjTYHXXxEATvGLX8y76OjNx20mXT7D1hZpCbp0uJJWxw4cL/h+VlOcGR3KqBHeGFBBXA6Tk8miMo/ZqXHVWF0pFc2eVbhpn3llOy+HHA92KRFakY14UWK5xGk+rU7y7/FJ2ehWbPr+HQES+1Z8B2RmLwUqU4QJBANqr3GZGtAnrkmK0Y4eNBa7oVyWM8lDqa40h6rCMifzPxNGw1DH5Yr55WN89z0MRJcJXHfoLgJzecbq4g8OMVpECQQClvaxLvMpZw3xqb6akE92pLZZlSKjKckHkE3/XTM6ZPF6o44SgSV2surUnYhA86KDDvEpMiR+YDFUdJ3z8vHAPAkEA2EMmG2SLhFAdm07KLHIVD9Gq9nE56TqeGZtUjzy+72/QOI4InlAFD1nVwhtQEwUvcc9Uz0l27i21DrSTY980cQJBAJUMuvqtgCgzdhrd57Wcq/WtqpfRPQI6uGjc5FYBm7YQpWwql6Xx9I0Wpz0Qolu0NIdyODsWAdSiGpUKYwuChx8CQETYzUXnFSrK4dp5na87j4nDZs/qeevfjBuhKiGIsSQ3SOTKdmpnVZRkGs6H/eEVcmYr1/H9T20Wx1A3oTmPMuE= 初始化共鑰為:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCNkskbzMWU65UceqB2r/JQhAh1+cGf6T5ALJdUSIfzTH1ecIzft5BmaxujRLyPsQrsMBRp/BsFA4Kguh8OZwNeXIbkaa2RQ2l2vYRawuq+o7UOjDzrKnWgyUn6SSGOuH2aqFSynYm1e/N5ny9e+Z/SJGg7sN5rLpicgzrIKZSCfwIDAQAB 信息原文:你是收破爛的么? 加密后:XeIAoNZlyn+Mk17wsdPpl8SDlaq0B8NbIvQFVg9Ja+YHxuKretNMu61IRY5EFyPL/dXC/6KiDDINglP2HRX4JNbRZgzZd1rkqExW219psHQOhFzbFYZ3yKuI72C7S4/sqIM1eqlnkvIGBhJNLwOfzF6VjplsbHAiQ4fDhA57XI8= 解密后:你是收破爛的么?
