RSA
收银台:请求数据+私钥做md5签名 BigInteger对请求参数做对称可逆加密
1.对称加密:一般小于256 bit的密钥,密钥越大越安全,但是解密和加密时间越长。加密和解密都是用的相同的密钥,快速简单
2.非对称加密:有公钥和私钥,只有私钥才能打开公钥,比如:你向银行请求公钥,银行将公钥发给你,你使用公钥对消息加密,那么只有私钥的持有人--银行才能对你的消息解密。与对称加密不同的是,银行不需要将私钥通过网络发送出去,因此安全性大大提高。但是速度慢
DES:Data Encrytion Standard(数据加密标准),对应算法是DEA
特点:1. 对称加密 2. 同一个SK
AES:Advanced Encrytion Standard(高级加密标准)
特点:1. 对称加密 2. 一个SK扩展成多个子SK,轮加密
RSA:特点: 1. 非对称加密,即:PK与SK不是同一个
2. PK用于加密,SK用于解密
3. PK决定SK,但是PK很难算出SK(数学原理:两个大质数相乘,积很难因式分解)
4. 速度慢,只对少量数据加密
公钥负责加密,私钥负责解密。私钥负责签名,公钥负责验证。公钥就是给大家用的,私钥就是给自己用的,必须小心保存
http://web.chacuo.net/netrsakeypair 生成私钥公钥
package com.creditease.yiqifin.bmow.base; import com.creditease.yiqifin.bmow.base.security.RSAUtil; public class RSAtest { public static void main(String[] args) { test("werretretrytryfgdfgtgrtgdfgsdgreg2"); } public static void test(String source){ String skey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAN2jaknBAxBgFY08"+ "kqy1jGWzNHFLU9h7E1QFwjrzdsJphpKQhmDNO1kaaAeuYkf59BgnhxGKmz6AqCLz"+ "7wV5BeQexYws4B6xHkQ8+vtWUioKb5LI7ZYDgs5V06U6u+LhwL72RgUR/sQ1OjzO"+ "iIEPhtffTlVs2EjCpnokzPCJqPUtAgMBAAECgYEAzxUtbQXix/0Ohe0PmkDykd8z"+ "Y5ufFohAEeRjitMJpjIUo4JXm8CF8AXFJ1Ae0eNP1vWvtIsN7AMnlajXLgTao4Fv"+ "bnOxep2fw2GSlFIuBnIN0bWJIpeQfWcC0pxvQ6pORBxg6Ys3JntahLXbc4RD1sol"+ "dRYQ8YXBREQTB/VtIoECQQD1ZH1VrRkPp2Yg3kGe2X/XOs2TZ8ZNjFFF4YOBbeE6"+ "gPzdimkWdDo2+q6frAeojCKeCvGpCKpHzyxHgEkvlLLhAkEA5zgP3lpVEqxfc9hv"+ "/5zq7zjI7J1+qwz9TgVMQft9k6iI0mEJrklMtrlVA41ZBgWi45JRMRmVHK7Z4oDT"+ "P3OXzQJAVVGFCj7O0dR/+7mK0zIH8sstIq0YE2pP754C3QNZJcAnKteuxfHPM8Jg"+ "6H8lgoKGnrBraTvsCF+No6aEy5hFwQJBALTT3WUyFFJ0SHpbDMxFtl68dDbIvWWc"+ "1QWNkyQPQRiXt9mAVofdf4dvzhLnGnZhNhDwP1s8/KbgADrqMUvwZQkCQC+/qHzE"+ "KQ/Wx2kJZ1oUuxyJ95iPp9ORnvpuTxi7sK5VW0QAIxWvpi9snGJJ45F5XU5dwWd2"+ "J9O7Z+0BVquuiJs="; String sign = ""; try { sign = RSAUtil.sign(source, skey); } catch (Exception e) { e.printStackTrace(); } System.out.println(source); System.out.println("密文:"+sign); String pkey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDdo2pJwQMQYBWNPJKstYxlszRx"+ "S1PYexNUBcI683bCaYaSkIZgzTtZGmgHrmJH+fQYJ4cRips+gKgi8+8FeQXkHsWM"+ "LOAesR5EPPr7VlIqCm+SyO2WA4LOVdOlOrvi4cC+9kYFEf7ENTo8zoiBD4bX305V"+ "bNhIwqZ6JMzwiaj1LQIDAQAB"; boolean verifySign = false; try { verifySign = RSAUtil.verifySign(source,sign,pkey); } catch (Exception e) { e.printStackTrace(); } System.out.println("验证签名:"+verifySign); } }
package com.creditease.yiqifin.bmow.base.security; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import com.creditease.yiqifin.bmow.base.exception.EncryptException; import com.creditease.yiqifin.bmow.base.exception.SignException; public class RSAUtil { private static final Logger logger = LoggerFactory.getLogger(RSAUtil.class); private static final String SIGN_ALGORITHMS = "SHA1WithRSA"; private static final String RSA_ALGORITHM = "RSA"; public static final String _CHARSET_NAME = "UTF-8"; static private final int BASELENGTH = 128; static private final int LOOKUPLENGTH = 64; static private final int TWENTYFOURBITGROUP = 24; static private final int EIGHTBIT = 8; static private final int SIXTEENBIT = 16; static private final int FOURBYTE = 4; static private final int SIGN = -128; static private final char PAD = '='; static private final boolean fDebug = false; static final private byte[] base64Alphabet = new byte[BASELENGTH]; static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; /** * 默认密钥字节数 * * <pre> * * DSA * Default Keysize 1024 * Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive). * </pre> */ private static final int KEY_SIZE = 1024; // 获取DSA公钥的key private final static String PUBLIC_RKEY = "RSAPublicKey"; // 获取DSA私钥的key private final static String PRIVATE_RKEY = "RSAPrivateKey"; 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) '/'; } /** * RSA签名 * * @param content 待签名数据 * @param privateKey 商户私钥 * @return 签名值 * @throws Exception */ public static String sign(String content, String privateKey) throws Exception { PrivateKey priKey = getPrivateKey(privateKey); java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS); signature.initSign(priKey); signature.update(content.getBytes(_CHARSET_NAME)); byte[] signed = signature.sign(); String signInfo = encode(signed); logger.info("rsa sign content : \r\ncontent:{}\r\nprivateKey:{}\r\nsignInfo:{}", content, privateKey, signInfo); return signInfo; } /** * RSA验签名检查 * * @param content 待签名数据 * @param sign 签名值 * @param pubKeyStr 支付宝公钥 * @param input_charset 编码格式 * @return 布尔值 * @throws Exception */ public static boolean verifySign(String content, String sign, String pubKeyStr) throws Exception { try { PublicKey pubKey = getPublicKey(pubKeyStr); java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS); signature.initVerify(pubKey); signature.update(content.getBytes(_CHARSET_NAME)); byte[] decode = decode(sign); boolean bverify = false; if (decode != null && decode.length > 0) { bverify = signature.verify(decode); } logger.info( "rsa verify signed content : \r\ncontent:{}\r\nsignInfo:{}\r\npublicKey:{}\r\nresult:{}", content, sign, pubKeyStr, bverify); return bverify; } catch (SignException e) { String message = e.getMessage(); if (StringUtils.isEmpty(message)) { message = "数据验签失败"; } else if (message.indexOf("Signature length not correct") >= 0) { message = "数据验签失败,signInfo长度错误,请发送密钥加签后的字符串,而不是密钥本身"; } throw new SignException(message, e); } catch (Exception e) { throw e; } } /** * 使用公钥加密 * * @param plainContent * @param publicKeyString * @return * @throws Exception */ public static String encryptWithPublicKey(String plainContent, String publicKeyString) throws Exception { PublicKey publicKey = getPublicKey(publicKeyString); byte[] plainContentData = plainContent.getBytes(_CHARSET_NAME); if (publicKey == null) { throw new EncryptException("加密公钥为空, 请设置"); } Cipher cipher = null; try { // 使用默认RSA cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] output = cipher.doFinal(plainContentData); return encode(output); } catch (NoSuchAlgorithmException e) { throw new EncryptException("无此加密算法", e); } catch (InvalidKeyException e) { throw new EncryptException("加密公钥非法,请检查", e); } catch (IllegalBlockSizeException e) { throw new EncryptException("明文长度非法", e); } catch (BadPaddingException e) { throw new EncryptException("明文数据已损坏", e); } } /** * 使用私钥对数据进行加密 * * @param plainContent 明文数据 * @param privateKeyString 私钥字符串 * @return * @throws Exception 加密过程中的异常信息 */ public static String encryptWithPrivateKey(String plainContent, String privateKeyString) throws Exception { PrivateKey privateKey = getPrivateKey(privateKeyString); byte[] plainContentData = plainContent.getBytes(_CHARSET_NAME); if (privateKey == null) { throw new EncryptException("加密私钥为空, 请设置"); } Cipher cipher = null; try { // 使用默认RSA cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] output = cipher.doFinal(plainContentData); return encode(output); } catch (NoSuchAlgorithmException e) { throw new EncryptException("无此加密算法", e); } catch (InvalidKeyException e) { throw new EncryptException("加密私钥非法,请检查", e); } catch (IllegalBlockSizeException e) { throw new EncryptException("明文长度非法", e); } catch (BadPaddingException e) { throw new EncryptException("明文数据已损坏", e); } catch (Throwable e) { throw new EncryptException("数据加密失败", e); } } /** * 私钥解密过程 * * @param privateKey 私钥 * @param cipherData 密文数据 * @return 明文 * @throws Exception 解密过程中的异常信息 */ public static String decryptWithPrivateKey(String cipherContent, String privateKeyString) throws Exception { byte[] cipherContentData = decode(cipherContent); PrivateKey privateKey = getPrivateKey(privateKeyString); if (privateKey == null) { throw new EncryptException("解密私钥为空, 请设置"); } Cipher cipher = null; try { // 使用默认RSA cipher = Cipher.getInstance("RSA"); // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] output = cipher.doFinal(cipherContentData); return new String(output); } catch (NoSuchAlgorithmException e) { throw new EncryptException("无此解密算法"); } catch (InvalidKeyException e) { throw new EncryptException("解密私钥非法,请检查"); } catch (IllegalBlockSizeException e) { throw new EncryptException("密文长度非法"); } catch (BadPaddingException e) { throw new EncryptException("密文数据已损坏"); } catch (Throwable e) { throw new EncryptException("数据解密失败", e); } } /** * 公钥解密 * * @param cipherContent * @param publicKeyString * @return * @throws Exception */ public static String decryptWithPublicKey(String cipherContent, String publicKeyString) throws Exception { byte[] cipherContentData = decode(cipherContent); PublicKey publicKey = getPublicKey(publicKeyString); if (publicKey == null) { throw new EncryptException("解密公钥为空, 请设置"); } Cipher cipher = null; try { cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] output = cipher.doFinal(cipherContentData); return new String(output); } catch (NoSuchAlgorithmException e) { throw new EncryptException("无此解密算法"); } catch (InvalidKeyException e) { throw new EncryptException("解密公钥非法,请检查"); } catch (IllegalBlockSizeException e) { throw new EncryptException("密文长度非法"); } catch (BadPaddingException e) { throw new EncryptException("密文数据已损坏"); } catch (Throwable e) { throw new EncryptException("数据解密失败", e); } } /** * 得到私钥 * * @param key 密钥字符串(经过base64编码) * @throws Exception */ private static PrivateKey getPrivateKey(String priKey) throws Exception { byte[] priKeyBytes = decode(priKey); PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(priKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(priKeySpec); } /** * 得到公钥 * * @param key 密钥字符串(经过base64编码) * @throws Exception */ private static PublicKey getPublicKey(String pubKey) throws Exception { byte[] pubkeyBytes = decode(pubKey); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubkeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(pubKeySpec); } /** * 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; if (fDebug) { System.out.println("number of triplets = " + numberTriplets); } for (int i = 0; i < numberTriplets; i++) { b1 = binaryData[dataIndex++]; b2 = binaryData[dataIndex++]; b3 = binaryData[dataIndex++]; if (fDebug) { System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3); } 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); if (fDebug) { System.out.println("val2 = " + val2); System.out.println("k4 = " + (k << 4)); System.out.println("vak = " + (val2 | (k << 4))); } 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); if (fDebug) { System.out.println("b1=" + b1); System.out.println("b1<<2 = " + (b1 >> 2)); } 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; } 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); } /** * <p> * 生成密钥对(公钥和私钥) * </p> * * @return * @throws Exception */ public static Map<String, Object> genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA_ALGORITHM); SecureRandom secureRandom = new SecureRandom(); keyPairGen.initialize(KEY_SIZE, secureRandom); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, Object> keyMap = new HashMap<String, Object>(2); keyMap.put(PUBLIC_RKEY, publicKey); keyMap.put(PRIVATE_RKEY, privateKey); return keyMap; } /** * <p> * 生成密钥对字符串(公钥和私钥) * </p> * * @return * @throws Exception */ public static Map<String, String> genKeyStringPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA_ALGORITHM); SecureRandom secureRandom = new SecureRandom(); keyPairGen.initialize(KEY_SIZE, secureRandom); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); byte[] publicBytes = publicKey.getEncoded(); String publicKeyString = RSAUtil.encode(publicBytes); byte[] privateBytes = privateKey.getEncoded(); String privateKeyString = RSAUtil.encode(privateBytes); Map<String, String> keyMap = new HashMap<String, String>(2); keyMap.put(PUBLIC_RKEY, publicKeyString); keyMap.put(PRIVATE_RKEY, privateKeyString); return keyMap; } }