1976年以前,所有的加密方法都是同一种模式:
由于加密和解密使用同样的规则(简称“秘钥”),这种被称为“对称加密算法”。这种加密模式有个最大的弱点:甲方必须把加密规则告诉乙方,否则无法解密。保存和传递秘钥成了最头疼的问题。
1976年,两位美国计算机科学家Whitfield Diffie和Martin Hellman,提出了一种崭新的构思,可以在不直接传递秘钥完成加密,这个被称为”Diffie-Hellman密钥交换算法”。这个算法启发了其他科学家。人们认识到,加密和解密可以使用不同的规则,这要这种规则直接存在某种对应的关系即可,这样就避免了直接传递秘钥。
这种新的加密模式被称为“非对称加密算法”:
如果公钥加密的信息只有私钥解得开,那么只要私钥不泄漏,通信就是安全的。
1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法,可以实现非对称加密。这种算法用他们三个人的名字命名,叫做RSA算法。从那时直到现在,RSA算法一直是最广为使用的”非对称加密算法”。毫不夸张地说,只要有计算机网络的地方,就有RSA算法。
这种算法非常可靠,密钥越长,它就越难破解。根据已经披露的文献,目前被破解的最长RSA密钥是768个二进制位。也就是说,长度超过768位的密钥,还无法破解(至少没人公开宣布)。因此可以认为,1024位的RSA密钥基本安全,2048位的密钥极其安全。
RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。
RSA基础类:
public class RSABase {
private static final String ALGORITHM = "RSA";
private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
private static final String DEFAULT_CHARSET = "UTF-8";
/** RSA最大加密明文大小 */
private static final int MAX_ENCRYPT_BLOCK = 117;
/** RSA最大解密密文大小 */
private static final int MAX_DECRYPT_BLOCK = 128;
private static final String TRANSFORMATION = "RSA";
public static String sign(String content, String privateKey) {
try {
PrivateKey priKey = getPrivateKey(privateKey);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
*
* @param content
* 密文
* @param private_key
* 私钥
* @return 解密后的字符串
*/
public static String decryptByPrivateKey(String content, String private_key) throws Exception {
return decrypByKey(content, getPrivateKey(private_key));
}
/**
* 解密
*
* @param content
* 密文
* @param private_key
* 私钥
* @return 解密后的字符串
*/
public static String decryptByPublicKey(String content, String public_key) throws Exception {
return decrypByKey(content, getPublickKey(public_key));
}
/**
* 解密
*
* @param content
* @param key
* @return
* @throws Exception
*/
private static String decrypByKey(String content, Key key) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, key);
InputStream ins = new ByteArrayInputStream(Base64.decode(content));
ByteArrayOutputStream writer = new ByteArrayOutputStream();
// rsa解密的字节大小最多是128,将需要解密的内容,按128位拆开解密
byte[] buf = new byte[MAX_DECRYPT_BLOCK];
int bufl;
while ((bufl = ins.read(buf)) != -1) {
byte[] block = null;
if (buf.length == bufl) {
block = buf;
} else {
block = new byte[bufl];
for (int i = 0; i < bufl; i++) {
block[i] = buf[i];
}
}
writer.write(cipher.doFinal(block));
}
return new String(writer.toByteArray(), DEFAULT_CHARSET);
}
/**
* 得到私钥
*
* @param key
* 密钥字符串(经过base64编码)
* @throws Exception
*/
protected static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes = Base64.decode(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 从文件中加载私钥
*
* @throws Exception
*/
protected static PrivateKey getPrivateKey(InputStream in) throws Exception {
return getPrivateKey(readFileKey(in));
}
/**
* 从文件中加载私钥
*
* @throws Exception
*/
protected static PublicKey getPublickKey(InputStream in) throws Exception {
return getPublickKey(readFileKey(in));
}
/**
* 读取文件中的秘钥信息
* @param in
* @return
* @throws Exception
*/
private static String readFileKey(InputStream in) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
return sb.toString();
}
/**
* 根据制定的可以进行加密
*
* @param content
* @param key
* @return
* @throws Exception
*/
public static String encyptByKey(String content, Key key) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] data = content.getBytes(DEFAULT_CHARSET);
int inputlen = data.length;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// rsa加密的字节大小最多是117,分段加密
while (inputlen - offset > 0) {
if (inputlen - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offset, inputlen - offset);
}
bos.write(cache, 0, cache.length);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptData = bos.toByteArray();
bos.close();
return Base64.encode(encryptData);
}
/**
*
* @param content
* 原始数据
* @param publicKey
* 密钥字符串(经过base64编码)
* @return 加密后的数据
* @throws Exception
*/
public static String encyptByPublicKey(String content, String publicKey) throws Exception {
return encyptByKey(content, getPublickKey(publicKey));
}
/**
*
* @param content
* 原始数据
* @param privateKey
* 密钥字符串(经过base64编码)
* @return 加密后的数据
* @throws Exception
*/
public static String encyptByPrivateKey(String content, String privateKey) throws Exception {
return encyptByKey(content, getPrivateKey(privateKey));
}
/**
* 得到公钥
*
* @param publicKey
* 密钥字符串(经过base64编码)
* @return
* @throws Exception
*/
private static PublicKey getPublickKey(String publicKey) throws Exception {
byte[] buffer = Base64.decode(publicKey);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return keyFactory.generatePublic(keySpec);
}
/**
* RSA验签名检查
*
* @param content
* 待签名数据
* @param sign
* 签名值
* @param public_key
* 公钥
* @return 布尔值
*/
public static boolean verify(String content, String sign, String public_key) {
try {
PublicKey pubKey = getPublickKey(public_key);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initVerify(pubKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
return signature.verify(Base64.decode(sign));
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
BASE64类:
public final class Base64 {
private static final int BASELENGTH = 128;
private static final int LOOKUPLENGTH = 64;
private static final int TWENTYFOURBITGROUP = 24;
private static final int EIGHTBIT = 8;
private static final int SIXTEENBIT = 16;
private static final int FOURBYTE = 4;
private static final int SIGN = -128;
private static char PAD = '=';
private static byte[] base64Alphabet = new byte[BASELENGTH];
private static char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect) {
return (octect == PAD);
}
private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData
* Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded
* string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded) {
if (encoded == null) {
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0) {
return null;// should be divisible by four
}
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0) {
return new byte[0];
}
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++) {
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++]))) {
return null;
} // if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
return null;// if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0)// last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)// last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
} else {
return null;
}
} else { // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data
* the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}
return newSize;
}
}
RSA工具类:
public class RsaUtil {
public static String PUBLICK_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClexlMC+y6aqjPOM4dIF3xbu3o"
+ "OnA41wG9l2GsomyaUILJR9/ppFVfabSU3acTdSkzq451PbTtKOo+kP8Ih/2qhV5N"
+ "Z2h1bptM28W2rSKPKcDt5o754L+GsXbWo39zd7uS5yZFKhLZw7YVi3fJ6ty5XMMs" + "7ERx/hMY/bYqyTAabQIDAQAB";
public static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKV7GUwL7LpqqM84"
+ "zh0gXfFu7eg6cDjXAb2XYayibJpQgslH3+mkVV9ptJTdpxN1KTOrjnU9tO0o6j6Q"
+ "/wiH/aqFXk1naHVum0zbxbatIo8pwO3mjvngv4axdtajf3N3u5LnJkUqEtnDthWL"
+ "d8nq3LlcwyzsRHH+Exj9tirJMBptAgMBAAECgYBPEqdf40LXQSgw/N/goxrAx1T/"
+ "Zw1A29yFD9UofOSQSHB2ZdXk+xWgZg5YJCI19gIeIpgMBdRyjt5/zyFOnkzjbeXF"
+ "Jx0i8i+8AKUsU+NencswTiPy9lHQKTLIbFEifDxl2IWaCaQ2kn+3z+jfxbcm9znT"
+ "vsFlu1kcaY/lNLZVsQJBANDsIt1yyEK8Wi68TdXRGuxl1OD8c9nZkLVTHax+1JWo"
+ "QyjI2rF4H3Do+S9QwofV26SDgPKsZwKNbTuHxlnWWTsCQQDKxQAWpP3HoHFAG2LQ"
+ "2KTJwBZtfM1sQjeN64hQ8cj89o1XRQjF2oWO0Ve+ibeDzMmGaLeky9WDfmnp6G05"
+ "2+B3AkBv+6JUgInG+557HoO57/M2cv6/+ZE/W9as2ng1VWYtMZuN6NsP9QslQjsO"
+ "mYMru/2XGMWtTauJOrUqC4TN8o6xAkEAw7l86F7CiJsaNiM5MxarmgLMo0rAjysr"
+ "rNYZcuiwdV0X+ZEtcq4IFV+FLuqINbTLIe6atXv70T2IxrwQErVm6QJAWfjVujrj"
+ "8yjGWK/gZDK5b/eSuDTg5lMJneGEzZm8uXRVUQqka5dP+j8vFr9IuEYb/N4CN5Je" + "E7x8NgrbgXVlbA==";
public static String encrypt(String content) {
try {
return RSABase.encyptByPublicKey(content, PUBLICK_KEY);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String decrypt(String content) {
try {
return RSABase.decryptByPrivateKey(content, PRIVATE_KEY);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String sign(String content) {
return RSABase.sign(content, PRIVATE_KEY);
}
public static void main(String[] args) {
// 加解密测试
String content = "2rwssfssdafsfj";
String encrypt = encrypt(content);
System.out.println(encrypt);
System.out.println(decrypt(encrypt));
// 签名测试
String sign = sign(content);
System.out.println(sign);
System.out.println(RSABase.verify(content, sign, PUBLICK_KEY));
}
}
相关的介绍就不用写了,代码和注释已经很明白了
windows环境的操作方法:
1. 工具下载:openssl工具
2. 双击运行bin目录下的openssl.exe
2. 生成RSA私钥命令:genrsa -out rsa_private_key.pem 1024
3. 生成RSA公钥命令:rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
4. 将RSA私钥转换成PKCS8格式:pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -out rsa_private_key_pkcs.txt -nocrypt
注意上面提供的测试代码私钥是基于pkcs8格式的。
数据摘要就是对数据源进行一个算法之后得到的一个摘要,也叫数据指纹,不同的数据源,摘要结果不一样。
数据摘要算法是一种能产生特殊输出格式的算法,其原理是根据一定的运算规则对原始数据进行某种信息的提取,被提取的信息称为原始数据的信息摘要。
常用的摘要算法有RSA公司的MD5算法和SHA-1算法以及其大量的变体。
数据摘要的特点:
1. 无论输入的消息有多长,计算出来的消息摘要的长度总是固定的。例如应用MD5算法摘要的消息有128个比特位,用SHA-1算法摘要的消息最终有160比特位的输出。
1. 一般来说(不考虑碰撞的情况下),只要输入的原始数据不同,对其进行摘要以后产生的消息摘要也必不相同,即使原始数据稍有改变,输出的消息摘要便完全不同。但是,相同的输入必会产生相同的输出。
1. 具有不可逆性,即只能进行正向的信息摘要,而无法从摘要中恢复出任何的原始消息。
大家知道要保证信息的可靠通信,必须要解决两个问题:一,确定消息的来源就是其申明的那个人;二,要保证数据在传输的过程中不被第三方篡改,即使篡改了也能发觉出来。
所谓书数字签名就是为了解决上述两个问题二产生,对非对称加密技术和数据摘要技术的一个具体应用。对消息发送者来说,首先要生成一对公私钥,将公钥发给消息接收者。
使用方法:
1. 消息发送者要给消息接收者发送消息,出了发送原始数据外,还需要发送原始数据的数字签名
2. 对消息接受者来说,它将收到两个数据,原始数据和签名数据,它需要判断这两个数据的合法信来确保通信的可靠,那么如何操作呢:(1):对原始数据提取数据摘要,注意这里使用的消息摘要算法和发送方的一致;(2):对附加的那段数字签名使用预先得到的公钥解密;(3):比较前两步所得到的两段消息是否一致。如果一致,则表明消息是可靠的,否则消息在传输过程中一定出现了问题,消息不可信。
在加解密的代码中已经提供了签名和验签的操作,就不在阐述。使用过支付宝的SDK的朋友都知道,向支付宝接口提交订单信息是就需要对订单信息进行签名,支付宝为了确保订单信息的可靠性就使用了签名机制。