MD5:

package com.pmtest.common.utils.sign;import java.security.MessageDigest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** Md5加密方法** @author ppq*/
public class Md5Utils
{private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);private static byte[] md5(String s){MessageDigest algorithm;try{algorithm = MessageDigest.getInstance("MD5");algorithm.reset();algorithm.update(s.getBytes("UTF-8"));byte[] messageDigest = algorithm.digest();return messageDigest;}catch (Exception e){log.error("MD5 Error...", e);}return null;}private static final String toHex(byte hash[]){if (hash == null){return null;}StringBuffer buf = new StringBuffer(hash.length * 2);int i;for (i = 0; i < hash.length; i++){if ((hash[i] & 0xff) < 0x10){buf.append("0");}buf.append(Long.toString(hash[i] & 0xff, 16));}return buf.toString();}/*** 加密* @param s* @return*/public static String hash(String s){try{return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");}catch (Exception e){log.error("not supported charset...{}", e);return s;}}
}

BASE64:

package com.pmtest.common.utils.sign;/*** Base64工具类** @author ppq*/
public final class Base64
{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 final private byte[]  base64Alphabet       = new byte[BASELENGTH];static final private 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 groupsif (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 spacesint 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 nullb1 = 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 charactersif (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 3cQlb3 = 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 whitespaceint newSize = 0;int len = data.length;for (int i = 0; i < len; i++){if (!isWhiteSpace(data[i])){data[newSize++] = data[i];}}return newSize;}
}

RSA1024:

package com.pmtest.common.utils;import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
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;/*** <p>* RSA公钥/私钥/签名工具包* </p>* <p>* 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman)* </p>* <p>* 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全* </p>**/
public abstract class RSA1024Utils {/** *//*** 加密算法RSA*/public static final String KEY_ALGORITHM = "RSA";/** *//*** 签名算法*/public static final String SIGNATURE_ALGORITHM = "MD5withRSA";/** *//*** 获取公钥的key*/private static final String PUBLIC_KEY = "RSAPublicKey";/** *//*** 获取私钥的key*/private static final String PRIVATE_KEY = "RSAPrivateKey";/** *//*** RSA最大加密明文大小*/private static final int MAX_ENCRYPT_BLOCK = 117;/** *//*** RSA最大解密密文大小*/private static final int MAX_DECRYPT_BLOCK = 128;/*** BASE64解密** @param key* @return* @throws Exception*/public static byte[] decryptBASE64(String key) throws Exception {return (new BASE64Decoder()).decodeBuffer(key);}/*** BASE64加密** @param key* @return* @throws Exception*/public static String encryptBASE64(byte[] key) throws Exception {return (new BASE64Encoder()).encodeBuffer(key);}/*** 用私钥对信息生成数字签名** @param inputStr   加密数据* @param privateKey 私钥* @return* @throws Exception*/public static String sign(String inputStr, String privateKey)throws Exception {byte[] data = inputStr.getBytes();// 解密由base64编码的私钥byte[] keyBytes = decryptBASE64(privateKey);// 构造PKCS8EncodedKeySpec对象PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);// KEY_ALGORITHM 指定的加密算法KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);// 取私钥匙对象PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);// 用私钥对信息生成数字签名Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);signature.initSign(priKey);signature.update(data);return encryptBASE64(signature.sign());}/*** 校验数字签名** @param inputStr  加密数据* @param publicKey 公钥* @param sign      数字签名* @return 校验成功返回true 失败返回false* @throws Exception*/public static boolean verify(String inputStr, String publicKey, String sign)throws Exception {byte[] data = inputStr.getBytes();// byte[] encodedData = RSACoder.encryptByPrivateKey(data, publicKey);// 解密由base64编码的公钥byte[] keyBytes = decryptBASE64(publicKey);// 构造X509EncodedKeySpec对象X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);// KEY_ALGORITHM 指定的加密算法KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);// 取公钥匙对象PublicKey pubKey = keyFactory.generatePublic(keySpec);Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);signature.initVerify(pubKey);signature.update(data);// 验证签名是否正常return signature.verify(decryptBASE64(sign));}/*** 解密<br>* 用私钥解密** @param source* @param key* @return* @throws Exception*/public static String decryptByPrivateKey(String source, String key)throws Exception {byte[] data = RSA1024Utils.decryptBASE64(source);// 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得私钥PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据解密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, privateKey);int inputLen = data.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(data, offSet, MAX_DECRYPT_BLOCK);} else {cache = cipher.doFinal(data, 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, "utf-8");}/*** 解密<br>* 用公钥解密** @param source 已加密数据* @param key    公钥* @return* @throws Exception*/public static String decryptByPublicKey(String source, String key)throws Exception {byte[] data = RSA1024Utils.decryptBASE64(source);// 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得公钥X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key publicKey = keyFactory.generatePublic(x509KeySpec);// 对数据解密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, publicKey);int inputLen = data.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(data, offSet, MAX_DECRYPT_BLOCK);} else {cache = cipher.doFinal(data, 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, "utf-8");}/*** 加密<br>* 用公钥加密** @param source 源数据* @param key    公钥* @return* @throws Exception*/public static String encryptByPublicKey(String source, String key)throws Exception {byte[] data = source.getBytes("utf-8");// 对公钥解密byte[] keyBytes = decryptBASE64(key);// 取得公钥X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key publicKey = keyFactory.generatePublic(x509KeySpec);// 对数据加密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, publicKey);int inputLen = data.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(data, offSet, MAX_ENCRYPT_BLOCK);} else {cache = cipher.doFinal(data, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_ENCRYPT_BLOCK;}byte[] encryptedData = out.toByteArray();out.close();return RSA1024Utils.encryptBASE64(encryptedData);}/*** 加密<br>* 用私钥加密** @param source* @param key* @return* @throws Exception*/public static String encryptByPrivateKey(String source, String key)throws Exception {//字符串转化byte[] data = source.getBytes("utf-8");// 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得私钥PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据加密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, privateKey);int inputLen = data.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(data, offSet, MAX_ENCRYPT_BLOCK);} else {cache = cipher.doFinal(data, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_ENCRYPT_BLOCK;}byte[] encryptedData = out.toByteArray();out.close();return encryptBASE64(encryptedData);}/*** 取得私钥** @param keyMap* @return* @throws Exception*/public static String getPrivateKey(Map<String, Object> keyMap)throws Exception {Key key = (Key) keyMap.get(PRIVATE_KEY);return encryptBASE64(key.getEncoded());}/*** 取得公钥** @param keyMap* @return* @throws Exception*/public static String getPublicKey(Map<String, Object> keyMap)throws Exception {Key key = (Key) keyMap.get(PUBLIC_KEY);return encryptBASE64(key.getEncoded());}/*** 初始化密钥** @return* @throws Exception*/public static Map<String, Object> initKey() throws Exception {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);keyPairGen.initialize(1024);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_KEY, publicKey);keyMap.put(PRIVATE_KEY, privateKey);return keyMap;}public static void main(String[] args) {try {String password = "10086";Map<String, Object> stringObjectMap = initKey();String publicKey = getPublicKey(stringObjectMap);System.out.println("公钥:" + publicKey);String privateKey = getPrivateKey(stringObjectMap);System.out.println("私钥:" + privateKey);String encPassword = encryptByPublicKey(password, publicKey);System.out.println("加密数据:" + encPassword);String decPassword = decryptByPrivateKey(encPassword, privateKey);System.out.println("解密数据:" + decPassword);} catch (Exception e) {e.printStackTrace();}}
}

RSA2048:

package com.pmtest.common.utils;import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
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;/*** Rsa工具类** @author*/
public abstract class RSA2048Utils {/*** 生成公钥私钥对,使用默认模长2048。** @return Object[] : 0:公钥( RSAPublicKey ),1:私钥( RSAPrivateKey )*/private static final int DEFAULT_KEY_LEN = 2048;public static Map<String, String> genKeyPair() {return genKeyPair(DEFAULT_KEY_LEN);}/*** 指定模长生成公私钥对** @param modulus* @return*/public static Map<String, String> genKeyPair(int modulus) {KeyPairGenerator keyPairGen;try {keyPairGen = KeyPairGenerator.getInstance("RSA");keyPairGen.initialize(modulus);KeyPair keyPair = keyPairGen.generateKeyPair();Map<String, String> keyMaps = new HashMap<String, String>();RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();keyMaps.put("publicKey", new String(encryptBASE64(publicKey.getEncoded())));RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();keyMaps.put("privateKey", new String(encryptBASE64(privateKey.getEncoded())));return keyMaps;} catch (Exception e) {throw new RuntimeException(e);}}/*** 公钥加密** @param publicKeyBytes* @param data* @param modulus        公钥模长,范围512-2048。* @return*/public static byte[] encryptByPublicKey(byte[] publicKeyBytes, byte[] data, int modulus) {try {// RSA最大加密明文大小int maxEncryptBlock = modulus / 8 - 11;X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");Key publicK = keyFactory.generatePublic(x509KeySpec);Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, publicK);int inputLen = data.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;while (inputLen - offSet > 0) {if (inputLen - offSet > maxEncryptBlock) {cache = cipher.doFinal(data, offSet, maxEncryptBlock);} else {cache = cipher.doFinal(data, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * maxEncryptBlock;}byte[] encryptedData = out.toByteArray();out.close();return encryptedData;} catch (Exception e) {throw new RuntimeException(e);}}/*** 公钥加密,密钥模长使用默认长度2048。** @param publicKeyBytes 公钥RSAPublicKey getEncoded()* @param data           要加密的字节数组*/public static byte[] encryptByPublicKey(byte[] publicKeyBytes, byte[] data) {return encryptByPublicKey(publicKeyBytes, data, DEFAULT_KEY_LEN);}/*** 公钥解密** @param publicKeyBytes 公钥RSAPublicKey getEncoded()* @param encryptedData  被(私钥)加密过的字节数组* @param modulus        模长,范围512-2048* @return*/public static byte[] decryptByPublicKey(byte[] publicKeyBytes, byte[] encryptedData, int modulus) {// RSA最大解密密文大小int maxDecryptBlock = modulus / 8;try {X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");Key publicK = keyFactory.generatePublic(x509KeySpec);Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, publicK);int inputLen = encryptedData.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;// 对数据分段解密while (inputLen - offSet > 0) {if (inputLen - offSet > maxDecryptBlock) {cache = cipher.doFinal(encryptedData, offSet, maxDecryptBlock);} else {cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * maxDecryptBlock;}byte[] decryptedData = out.toByteArray();out.close();return decryptedData;} catch (Exception e) {throw new RuntimeException(e);}}/*** 公钥解密,默认模长2048** @param publicKeyBytes 公钥RSAPublicKey getEncoded()* @param encryptedData  被(私钥)加密过的字节数组*/public static byte[] decryptByPublicKey(byte[] publicKeyBytes, byte[] encryptedData) {return decryptByPublicKey(publicKeyBytes, encryptedData, DEFAULT_KEY_LEN);}/*** 私钥加密** @param privateKeyBytes 私钥RSAPrivateKey getEncoded()* @param data            要加密的字节数组* @param modulus         模长,范围512-2048。*/public static byte[] encryptByPrivateKey(byte[] privateKeyBytes, byte[] data, int modulus) {try {// RSA最大加密明文大小int maxEncryptBlock = modulus / 8 - 11;PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, privateK);int inputLen = data.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;while (inputLen - offSet > 0) {if (inputLen - offSet > maxEncryptBlock) {cache = cipher.doFinal(data, offSet, maxEncryptBlock);} else {cache = cipher.doFinal(data, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * maxEncryptBlock;}byte[] encryptedData = out.toByteArray();out.close();return encryptedData;} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e);}}/*** 私钥加密,默认模长2048。** @param privateKeyBytes 私钥RSAPrivateKey getEncoded()* @param data            要加密的字节数组*/public static byte[] encryptByPrivateKey(byte[] privateKeyBytes, byte[] data) {return encryptByPrivateKey(privateKeyBytes, data, DEFAULT_KEY_LEN);}/*** 私钥解密** @param privateKeyBytes 私钥RSAPrivateKey getEncoded()* @param encryptedData   被(公钥)加密过的字节数组* @param modulus         模长,范围512-2048*/public static byte[] decryptByPrivateKey(byte[] privateKeyBytes, byte[] encryptedData, int modulus) {try {// RSA最大解密密文大小int maxDecryptBlock = modulus / 8;PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());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 > maxDecryptBlock) {cache = cipher.doFinal(encryptedData, offSet, maxDecryptBlock);} else {cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * maxDecryptBlock;}byte[] decryptedData = out.toByteArray();out.close();return decryptedData;} catch (Exception e) {throw new RuntimeException(e);}}/*** BASE64解密** @param key* @return* @throws Exception*/public static byte[] decryptBASE64(String key) throws Exception {return (new BASE64Decoder()).decodeBuffer(key);}/*** BASE64加密** @param key* @return* @throws Exception*/public static String encryptBASE64(byte[] key) throws Exception {return (new BASE64Encoder()).encodeBuffer(key);}/*** 私钥解密,默认模长2048。** @param privateKeyBytes 私钥RSAPrivateKey getEncoded()* @param encryptedData   被(公钥)加密过的字节数组*/public static byte[] decryptByPrivateKey(byte[] privateKeyBytes, byte[] encryptedData) {return decryptByPrivateKey(privateKeyBytes, encryptedData, DEFAULT_KEY_LEN);}/*** 功能:公钥加密 <br>** @param plainText* @param publicKey* @return* @throws Exception*/public static String encryptByPublicKey(String plainText, String publicKey) throws Exception {byte[] encrypTextArr = RSA2048Utils.encryptByPublicKey(decryptBASE64(publicKey), plainText.getBytes("UTF-8"));return encryptBASE64(encrypTextArr);}/*** 功能:公钥解密 <br>** @param encryptxt* @param encryptxt* @return* @throws Exception*/public static String decryptByPublicKey(String encryptxt, String publicKey) throws Exception {byte[] plainTextArr = RSA2048Utils.decryptByPublicKey(decryptBASE64(publicKey), decryptBASE64(encryptxt));return new String(plainTextArr, "utf-8");}/*** 功能:私钥加密 <br>** @param plainText* @param plainText* @return* @throws Exception*/public static String encryptByPrivateKey(String plainText, String privateKey) throws Exception {byte[] encrypTextArr = RSA2048Utils.encryptByPrivateKey(decryptBASE64(privateKey), plainText.getBytes("UTF-8"));return encryptBASE64(encrypTextArr);}/*** 功能:私钥解密 <br>** @param encryptxt* @param privateKey* @return* @throws Exception*/public static String decryptByPrivateKey(String encryptxt, String privateKey) throws Exception {byte[] plainTextArr = RSA2048Utils.decryptByPrivateKey(decryptBASE64(privateKey), decryptBASE64(encryptxt));return new String(plainTextArr, "utf-8");}public static void main(String[] args) throws Exception {Map<String, String> map = genKeyPair(2048);String psw = "10086";String pswEnc = encryptByPublicKey(psw, map.get("publicKey"));System.out.println("加密数据:" + pswEnc);String pswdec = decryptByPrivateKey(pswEnc, map.get("privateKey"));System.out.println("解密数据:" + pswdec);}}

md5、base64、RSA1024、RA2048工具类相关推荐

  1. base64码 java_工具类:Java将图片变成base64码

    一个可以将图片转成base64编码的工具类/** * Copyright (c) 2011-2017, 玛雅牛 (myaniu AT gmail dot com). * * Licensed unde ...

  2. MD5加盐加密工具类(可直接使用)

    MD5加盐加密工具类 在我们做项目时,涉及到用户密码,而正常来说数据库中不会直接存储明文的密码,都是加密之后的密码. 密码加密的方式有很多,比如: ① 3DES.AES.DES:使用对称加密算法,可以 ...

  3. MD5加密之DigestUtils工具类

    有志者,事竟成 文章持续更新,可以关注[小奇JAVA面试]第一时间阅读,回复[资料]获取福利,回复[项目]获取项目源码,回复[简历模板]获取简历模板,回复[学习路线图]获取学习路线图. 文章目录 一. ...

  4. MD5加盐加密工具类

    直接使用MD5加密,能被解密网站破解,因此在加密的时候可以加个盐值.工具类如下: import org.apache.commons.codec.binary.Base64; import java. ...

  5. md5编码java_MD5编码工具类 MD5Code.java

    package com.util; /** * MD5编码工具类 * */ public class MD5Code { static final int S11 = 7; static final  ...

  6. SpringBoot 文件上传 基于MD5 文件内容校验工具类

    1.业务场景:实现文件上传功能时.我们需要校验上传文件在传输过程中是否被注入脚本或者是被修改,所有采用md5 算法+ 文件内容生成一个识别码,传递给后端,让后端判断文件是否发生修改或变更. impor ...

  7. MD5加密介绍、工具类的使用

    目标 了解什么是md5,它有哪些特点 使用md5的工具类对字符串进行加密 提高md5的加密程度 应用场景 ​ 在企业中,登录账户表,里面的密码是加密的,为了防止数据管理员或IT部内部人员数据泄密.注册 ...

  8. base64图片转换工具类以及base转图片工具

    import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import ...

  9. pdf与base64相互转换的工具类

    import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder;import javax.servlet.ServletOutputStrea ...

最新文章

  1. 全民捡破烂,转转和闲鱼谁能胜出?
  2. C++ int,float,double,long表示范围
  3. 静态局部变量和全局变量的区别!
  4. 工业计算机是服务器吗,工控机服务器能通用吗_服务器和工控机有什么区别
  5. chrome 不支持12px以下字体为题的解决
  6. Chrome 渲染流水线演化的未来
  7. matlab生成西门子plc源文件,西门子PLC如何把DB快做成源文件
  8. 【LeetCode】241. Different Ways to Add Parentheses
  9. Memcached 教程 | 菜鸟教程
  10. BZOJ 1734: [Usaco2005 feb]Aggressive cows 愤怒的牛( 二分答案 )
  11. 蓝桥杯 BASIC-15 基础练习 字符串对比
  12. Golang最佳Web框架对比
  13. 内存管理中的虚拟地址到物理地址翻译
  14. 温度反转效应(文末附2018数字IC后端最新校招笔试题目)
  15. meo学习笔记6:VS2017+ Qt5.*配置安装过程的问题记录
  16. sklearn和libsvm吗_机器学习笔记(3)-sklearn支持向量机SVM
  17. 【自动驾驶行业观察】奥迪A8自动驾驶功能剖析
  18. 在没有安装VC软件的电脑上也可以执行的exe文件
  19. PDF文件只能打印出第一页
  20. 京东运维开发工程师 2019校招卷总结

热门文章

  1. 打印由26个英文字母组成的菱形
  2. sharepoint error:该 URL“...”无效。它可能指向不存在的文件或文件夹,或者是指向不在当前网站中的有效文件或文件夹 -- 金大昊(jindahao)...
  3. PPS网络电视 V2.0.10.988 正式版
  4. 为什么c语言程序无法生成,程序无法生成
  5. 免费资源:原来超人rman也会哭+4031经典解决方案
  6. 电脑一声,电脑开机后会响一声,是什么原因呢?
  7. HTML div的使用
  8. 云服务器硬件加速是灰色的,win7系统显卡硬件加速显示灰色不能设置的解决方法...
  9. Qt之实现图片或按钮等控件的倒影效果
  10. 菊风云 | 普惠金融推进受阻,远程银行或成破冰契机