RSA加密技术
package com.dowell.core;
import it.sauronsoftware.base64.Base64;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.crypto.Cipher;
public class RSAUtils {
// public static final String PRIVATE_KEY = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAuqp8fQcX5zaronsxUg5N5n0W8ODnY9V1eyVEa9iGdLSYbjVBQpRacjOsTnl1PEf38Jg46iuREJPtV/oWJl9V4QIDAQABAkEAnk2VM4b/e4M+vZXSNu+Qmwa8nN1u/ph5gE0ToI5JQNCuds7SSfsyS7A9c0hKTun0ksegKmcN75kNpgG3NmNrAQIhAPO93KZltiiR9Gmf+9SqcirKwVmmZhXLkKHb7jWlR09xAiEAxA3Ig2L4lhTMvB9ap8NtZyEmQypUxj1GVbpn9v/xFXECIBXNN71Sf7alR31jJ/1fuZKGTEEelyb/7FHuACKgQ/6hAiBH+nt8aVC04SwNgUFqSGCZNV1z2U3IfmSdQtO6plrfsQIgFqc6n4YavLHkx+Z2wIpVDlMqsZr0vAxTerc/55ofY2c=";
// private static final String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALqqfH0HF+c2q6J7MVIOTeZ9FvDg52PVdXslRGvYhnS0mG41QUKUWnIzrE55dTxH9/CYOOorkRCT7Vf6FiZfVeECAwEAAQ==";
public static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAK/K9ViAeHeYs9fAdzwWr+zfvt4X54I8ukn257bvaZdBfuYUVYdwViDyS3kz7thAYV36V5xpAdhJVhPz84ejmjAYX6pMUmIbRJBQXgKwP3l/gAOfg1RDPyDK/OvWGpsdkFHjNkzYUAFS2J9aOnGThqI+AXLHXDK69aO2ZbveZm8bAgMBAAECgYA/8RT40hH/fn279nfoVWA8Ss5EPnGo/6nLCZITClZf/CTKT48kqonJhhhJx8gSxKgl5M9FRzSylUpIC64DIlEMneGb5mGj9qNZTwyR/Yq0JWKIJmTduN3v3CA48zsym2VTfGfEytxc+N7Pup3jeBcwaaCsSVR6IUK4ZV6pD+CZMQJBAPC2GH8MiKY5QXpJYa8ya7df9RaWE6fg8FSCbU78dfO3isfJCqzWtZy0zX8UyO6o2T/ynW/D5DxxBjbO6rPN2lcCQQC69U3uNDvILDEbInilKMki16MMJfmwOh6SGUWYPABzXiYLTfkjBTqO/L6IHbX7dbehERFqvtKyL4sXK/Uzg17dAkBQSiz5k9CwwUBZ7cgrjAHp9JPnqL99q8X+KlMTmZouZPZhlWl+JVAGqTgyP1iWYrO0ZNSmxwyGLJ0KAxK+TteZAkEAuo/LImaxOUEQB5nQdk9K1yADrj2++eIlW3kof49wi69pm2JFuHKhSspffwjW7oU7ptiXXsPpELJsw8SzvKHdaQJAS3Ils8EyZMolDfkWQBZE7rRaQsokgY3dZwbLOEvZcQ+yOcuq4bk23rJ8uA7oESU0IN9uQGHF+ToAE43aN2JmOg==";
private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvyvVYgHh3mLPXwHc8Fq/s377eF+eCPLpJ9ue272mXQX7mFFWHcFYg8kt5M+7YQGFd+lecaQHYSVYT8/OHo5owGF+qTFJiG0SQUF4CsD95f4ADn4NUQz8gyvzr1hqbHZBR4zZM2FABUtifWjpxk4aiPgFyx1wyuvWjtmW73mZvGwIDAQAB";
/** 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(512);
// 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 = base64Decode(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 base64Encode(encryptedData);
}
/**
* 私钥解密
*
* @param data
* @return
* @throws Exception
*/
public static String decryptByPrivateKey(String data) throws Exception {
byte[] encryptedData = base64Decode(data);
byte[] keyBytes = base64Decode(PRIVATE_KEY);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
// Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
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 = base64Decode(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 = base64Decode(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(base64Encode(privateKey.getEncoded()));
}
public static String getPublicKeyStr(PublicKey publicKey) throws Exception {
return new String(base64Encode(publicKey.getEncoded()));
}
/** */
/**
* <p>
* BASE64字符串解码为二进制数据
* </p>
*
* @param base64
* @return
* @throws Exception
*/
public static byte[] base64Decode(String base64) throws Exception {
return Base64.decode(base64.getBytes());
}
/** */
/**
* <p>
* 二进制数据编码为BASE64字符串
* </p>
*
* @param bytes
* @return
* @throws Exception
*/
public static String base64Encode(byte[] bytes) throws Exception {
return new String(Base64.encode(bytes));
}
/**
* 27 md5加密产生,产生128位(bit)的mac 28 将128bit Mac转换成16进制代码 29
*
* @param strSrc
* 30
* @param key
* 31
* @return 32
*/
public static String MD5Encode(String strSrc) {
return MD5Encode(strSrc, "");
}
/**
* 27 md5加密产生,产生128位(bit)的mac 28 将128bit Mac转换成16进制代码 29
*
* @param strSrc
* 30
* @param key
* 31
* @return 32
*/
public static String MD5Encode(String strSrc, String key) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(strSrc.getBytes("UTF8"));
StringBuilder result = new StringBuilder(32);
byte[] temp;
temp = md5.digest(key.getBytes("UTF8"));
for (int i = 0; i < temp.length; i++) {
result.append(Integer.toHexString(
(0x000000ff & temp[i]) | 0xffffff00).substring(6));
}
return result.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) throws Exception {
getKeys();
}
}