一、父工程加载SpringCloud依赖
这里需要注意版本号:不同的Springboot版本需要的不同的Springcloud版本号。
博主用的是2.2.6的springboot版本。所以springcloud用的是Hoxton.SR4的版本。
二、创建Eureka微服务
(注:三个步骤:添加依赖,创建yaml文件,创建启动类。都需要配置)
Eureka微服务导入服务端依赖
yaml文件配置端口,以及eureka的相关配置
启动类添加服务端的注释
此时,可以启动这个微服务,进入本机下的6868端口号的页面,查看是否配置成功
看到此页面,则eureka微服务配置成功
三、将需要的微服务注册入Eureka微服务。
(注:也是添加三个步骤,导入依赖包,修改yaml配置文件,添加启动类中客户端的注释)
添加客户端依赖
yaml文件添加配置
启动类添加客户端注释
这个时候可以启动客户端的微服务,可以看到,前面6868端口注册中心添加了刚刚启动的微服务
如果有此显示,则代表注册成功
四、添加网关微服务
(注:五个步骤,启动类添加注释,配置文件添加配置,导入相关依赖,添加工具类、编写过滤器)
网关、客户端依赖注入
编写配置文件
启动类添加网关和客户端注释
创建rsa工具包,导入工具类
Base64Utils工具类
package com.tensquare.encrypt.rsa;
import java.io.*;
public class Base64Utils {
/** */
/**
* 28. * 文件读取缓冲区大小
* 29.
*/
private static final int CACHE_SIZE = 1024;
/** */
/**
* 33. *
* 34. * BASE64字符串解码为二进制数据
* 35. *
* 36. *
* 37. * @param base64
* 38. * @return
* 39. * @throws Exception
* 40.
*/
public static byte[] decode(String base64) throws Exception {
return mBase64.decode(base64.getBytes());
}
/** */
/**
* 46. *
* 47. * 二进制数据编码为BASE64字符串
* 48. *
* 49. *
* 50. * @param bytes
* 51. * @return
* 52. * @throws Exception
* 53.
*/
public static String encode(byte[] bytes) throws Exception {
return new String(mBase64.encode(bytes));
}
/** */
/**
* 59. *
* 60. * 将文件编码为BASE64字符串
* 61. *
* 62. *
* 63. * 大文件慎用,可能会导致内存溢出
* 64. *
* 65. *
* 66. * @param filePath 文件绝对路径
* 67. * @return
* 68. * @throws Exception
* 69.
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
}
/** */
/**
* 76. *
* 77. * BASE64字符串转回文件
* 78. *
* 79. *
* 80. * @param filePath 文件绝对路径
* 81. * @param base64 编码字符串
* 82. * @throws Exception
* 83.
*/
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
}
/** */
/**
*
* 文件转换为二进制数组
*
*
* @param filePath 文件路径
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
/** */
/**
* 118. *
* 119. * 二进制数据写文件
* 120. *
* 121. *
* 122. * @param bytes 二进制数据
* 123. * @param filePath 文件生成目录
* 124.
*/
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
}
//新增-----------------------------------------
private static char[] base64EncodeChars = new char[]{
'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/',};
private static byte[] base64DecodeChars = new byte[]{
-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1,
-1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,
-1, -1};
/**
* 解密
*
* @param data
* @return
*/
public static byte[] decodeStr(byte[] data) {
// byte[] data = str.getBytes();
int len = data.length;
ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
int i = 0;
int b1, b2, b3, b4;
while (i < len) {
do {
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -1);
if (b1 == -1) {
break;
}
do {
b2 = base64DecodeChars[data[i++]];
} while (i < len && b2 == -1);
if (b2 == -1) {
break;
}
buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
do {
b3 = data[i++];
if (b3 == 61) {
return buf.toByteArray();
}
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -1);
if (b3 == -1) {
break;
}
buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
do {
b4 = data[i++];
if (b4 == 61) {
return buf.toByteArray();
}
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -1);
if (b4 == -1) {
break;
}
buf.write((int) (((b3 & 0x03) << 6) | b4));
}
return buf.toByteArray();
}
}
mBase64工具类
package com.tensquare.encrypt.rsa;
/**
* Created by Administrator on 2017/10/30.
*/
public class mBase64 {
static final int CHUNK_SIZE = 76;
static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();
private static final int BASELENGTH = 255;
private static final int LOOKUPLENGTH = 64;
private static final int EIGHTBIT = 8;
private static final int SIXTEENBIT = 16;
private static final int TWENTYFOURBITGROUP = 24;
private static final int FOURBYTE = 4;
private static final int SIGN = -128;
private static final byte PAD = 61;
private static final byte[] base64Alphabet = new byte[255];
private static final byte[] lookUpBase64Alphabet = new byte[64];
public mBase64() {
}
private static boolean isBase64(byte octect) {
return octect == 61 ? true : octect >= 0 && base64Alphabet[octect] != -1;
}
public static boolean isBase64(byte[] arrayOctect) {
arrayOctect = discardWhitespace(arrayOctect);
int length = arrayOctect.length;
if (length == 0) {
return true;
} else {
for (int i = 0; i < length; ++i) {
if (!isBase64(arrayOctect[i])) {
return false;
}
}
return true;
}
}
static byte[] discardWhitespace(byte[] data) {
byte[] groomedData = new byte[data.length];
int bytesCopied = 0;
byte[] packedData = data;
int len$ = data.length;
int i$ = 0;
while (i$ < len$) {
byte aByte = packedData[i$];
switch (aByte) {
default:
groomedData[bytesCopied++] = aByte;
case 9:
case 10:
case 13:
case 32:
++i$;
}
}
packedData = new byte[bytesCopied];
System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
return packedData;
}
// public static String encodeToString(byte[] bytes) {
// byte[] encoded = encode(bytes);
// return CodecSupport.toString(encoded);
// }
public static byte[] encodeChunked(byte[] binaryData) {
return encode(binaryData, true);
}
public static byte[] encode(byte[] pArray) {
return encode(pArray, false);
}
public static byte[] encode(byte[] binaryData, boolean isChunked) {
long binaryDataLength = (long) binaryData.length;
long lengthDataBits = binaryDataLength * 8L;
long fewerThan24bits = lengthDataBits % 24L;
long tripletCount = lengthDataBits / 24L;
int chunckCount = 0;
long encodedDataLengthLong;
if (fewerThan24bits != 0L) {
encodedDataLengthLong = (tripletCount + 1L) * 4L;
} else {
encodedDataLengthLong = tripletCount * 4L;
}
if (isChunked) {
chunckCount = CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((double) ((float) encodedDataLengthLong / 76.0F));
encodedDataLengthLong += (long) (chunckCount * CHUNK_SEPARATOR.length);
}
if (encodedDataLengthLong > 2147483647L) {
throw new IllegalArgumentException("Input array too big, output array would be bigger than Integer.MAX_VALUE=2147483647");
} else {
int encodedDataLength = (int) encodedDataLengthLong;
byte[] encodedData = new byte[encodedDataLength];
int encodedIndex = 0;
int nextSeparatorIndex = 76;
int chunksSoFar = 0;
byte k;
byte l;
byte b1;
byte b2;
int dataIndex;
int i;
byte val1;
byte val2;
for (i = 0; (long) i < tripletCount; ++i) {
dataIndex = i * 3;
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
byte b3 = binaryData[dataIndex + 2];
l = (byte) (b2 & 15);
k = (byte) (b1 & 3);
val1 = (b1 & -128) == 0 ? (byte) (b1 >> 2) : (byte) (b1 >> 2 ^ 192);
val2 = (b2 & -128) == 0 ? (byte) (b2 >> 4) : (byte) (b2 >> 4 ^ 240);
byte val3 = (b3 & -128) == 0 ? (byte) (b3 >> 6) : (byte) (b3 >> 6 ^ 252);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | k << 4];
encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2 | val3];
encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 63];
encodedIndex += 4;
if (isChunked && encodedIndex == nextSeparatorIndex) {
System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length);
++chunksSoFar;
nextSeparatorIndex = 76 * (chunksSoFar + 1) + chunksSoFar * CHUNK_SEPARATOR.length;
encodedIndex += CHUNK_SEPARATOR.length;
}
}
dataIndex = i * 3;
if (fewerThan24bits == 8L) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 3);
val1 = (b1 & -128) == 0 ? (byte) (b1 >> 2) : (byte) (b1 >> 2 ^ 192);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex + 2] = 61;
encodedData[encodedIndex + 3] = 61;
} else if (fewerThan24bits == 16L) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 15);
k = (byte) (b1 & 3);
val1 = (b1 & -128) == 0 ? (byte) (b1 >> 2) : (byte) (b1 >> 2 ^ 192);
val2 = (b2 & -128) == 0 ? (byte) (b2 >> 4) : (byte) (b2 >> 4 ^ 240);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | k << 4];
encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex + 3] = 61;
}
if (isChunked && chunksSoFar < chunckCount) {
System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length);
}
return encodedData;
}
}
// public static String decodeToString(String base64Encoded) {
// byte[] encodedBytes = CodecSupport.toBytes(base64Encoded);
// return decodeToString(encodedBytes);
// }
//
// public static String decodeToString(byte[] base64Encoded) {
// byte[] decoded = decode(base64Encoded);
// return CodecSupport.toString(decoded);
// }
//
// public static byte[] decode(String base64Encoded) {
// byte[] bytes = CodecSupport.toBytes(base64Encoded);
// return decode(bytes);
// }
public static byte[] decode(byte[] base64Data) {
base64Data = discardNonBase64(base64Data);
if (base64Data.length == 0) {
return new byte[0];
} else {
int numberQuadruple = base64Data.length / 4;
int encodedIndex = 0;
int i = base64Data.length;
while (base64Data[i - 1] == 61) {
--i;
if (i == 0) {
return new byte[0];
}
}
byte[] decodedData = new byte[i - numberQuadruple];
for (i = 0; i < numberQuadruple; ++i) {
int dataIndex = i * 4;
byte marker0 = base64Data[dataIndex + 2];
byte marker1 = base64Data[dataIndex + 3];
byte b1 = base64Alphabet[base64Data[dataIndex]];
byte b2 = base64Alphabet[base64Data[dataIndex + 1]];
byte b3;
if (marker0 != 61 && marker1 != 61) {
b3 = base64Alphabet[marker0];
byte b4 = base64Alphabet[marker1];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] = (byte) ((b2 & 15) << 4 | b3 >> 2 & 15);
decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
} else if (marker0 == 61) {
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
} else {
b3 = base64Alphabet[marker0];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] = (byte) ((b2 & 15) << 4 | b3 >> 2 & 15);
}
encodedIndex += 3;
}
return decodedData;
}
}
static byte[] discardNonBase64(byte[] data) {
byte[] groomedData = new byte[data.length];
int bytesCopied = 0;
byte[] packedData = data;
int len$ = data.length;
for (int i$ = 0; i$ < len$; ++i$) {
byte aByte = packedData[i$];
if (isBase64(aByte)) {
groomedData[bytesCopied++] = aByte;
}
}
packedData = new byte[bytesCopied];
System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
return packedData;
}
static {
int i;
for (i = 0; i < 255; ++i) {
base64Alphabet[i] = -1;
}
for (i = 90; i >= 65; --i) {
base64Alphabet[i] = (byte) (i - 65);
}
for (i = 122; i >= 97; --i) {
base64Alphabet[i] = (byte) (i - 97 + 26);
}
for (i = 57; i >= 48; --i) {
base64Alphabet[i] = (byte) (i - 48 + 52);
}
base64Alphabet[43] = 62;
base64Alphabet[47] = 63;
for (i = 0; i <= 25; ++i) {
lookUpBase64Alphabet[i] = (byte) (65 + i);
}
i = 26;
int j;
for (j = 0; i <= 51; ++j) {
lookUpBase64Alphabet[i] = (byte) (97 + j);
++i;
}
i = 52;
for (j = 0; i <= 61; ++j) {
lookUpBase64Alphabet[i] = (byte) (48 + j);
++i;
}
lookUpBase64Alphabet[62] = 43;
lookUpBase64Alphabet[63] = 47;
}
}
添加RS工具类
package com.tensquare.encrypt.rsa;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
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;
//
public class RSA {
/** */
/**
* 加密算法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;
private static final int MAX_ENCRYPT_BLOCK = 245;
/** */
/**
* RSA最大解密密文大小
*/
//private static final int MAX_DECRYPT_BLOCK = 128;
private static final int MAX_DECRYPT_BLOCK = 256;
/** */
/**
*
* 生成密钥对(公钥和私钥)
*
*
* @return
* @throws Exception
*/
public static Map<String, Object> genKeyPair() 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;
}
/** */
/**
*
* 用私钥对信息生成数字签名
*
*
* @param data 已加密数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(data);
return Base64Utils.encode(signature.sign());
}
/** */
/**
* 112. *
* 113. * 校验数字签名
* 114. *
* 115. *
* 116. * @param data 已加密数据
* 117. * @param publicKey 公钥(BASE64编码)
* 118. * @param sign 数字签名
* 119. *
* 120. * @return
* 121. * @throws Exception
* 122. *
* 123.
*/
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
return signature.verify(Base64Utils.decode(sign));
}
/** */
/**
* 137. *
* 138. * 私钥解密
* 139. *
* 140. *
* 141. * @param encryptedData 已加密数据
* 142. * @param privateKey 私钥(BASE64编码)
* 143. * @return
* 144. * @throws Exception
* 145.
*/
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
throws Exception {
// byte[] keyBytes = Base64Utils.decode(privateKey);
// PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = getPrivateKey(privateKey);
//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 decryptedData;
}
/**
* 得到私钥
*
* @param key 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 得到公钥
*
* @param key 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/** */
/**
* 176. *
* 177. * 公钥解密
* 178. *
* 179. *
* 180. * @param encryptedData 已加密数据
* 181. * @param publicKey 公钥(BASE64编码)
* 182. * @return
* 183. * @throws Exception
* 184.
*/
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
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 > 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 decryptedData;
}
/** */
/**
* 215. *
* 216. * 公钥加密
* 217. *
* 218. *
* 219. * @param data 源数据
* 220. * @param publicKey 公钥(BASE64编码)
* 221. * @return
* 222. * @throws Exception
* 223.
*/
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
// byte[] keyBytes = Base64Utils.decode(publicKey);
// X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = getPublicKey(publicKey);
// 对数据加密
//Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
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 > 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 encryptedData;
}
/** */
/**
* 255. *
* 256. * 私钥加密
* 257. *
* 258. *
* 259. * @param data 源数据
* 260. * @param privateKey 私钥(BASE64编码)
* 261. * @return
* 262. * @throws Exception
* 263.
*/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
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 > 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 encryptedData;
}
/** */
/**
* 294. *
* 295. * 获取私钥
* 296. *
* 297. *
* 298. * @param keyMap 密钥对
* 299. * @return
* 300. * @throws Exception
*/
// public static String getPrivateKey(Map keyMap)
// throws Exception {
// Key key = (Key) keyMap.get(PRIVATE_KEY);
// return Base64Utils.encode(key.getEncoded());
// }
/** */
/**
* 309. *
* 310. * 获取公钥
* 311. *
* 312. *
* 313. * @param keyMap 密钥对
* 314. * @return
* 315. * @throws Exception
* 316.
*/
public static String getPublicKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Base64Utils.encode(key.getEncoded());
}
}
添加RSAKeys工具类
package com.tensquare.encrypt.rsa;
/**
* rsa加解密用的公钥和私钥
* @author Administrator
*
*/
public class RsaKeys {
//生成秘钥对的方法可以参考这篇帖子
//https://www.cnblogs.com/yucy/p/8962823.html
// //服务器公钥
// private static final String serverPubKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6Dw9nwjBmDD/Ca1QnRGy"
// + "GjtLbF4CX2EGGS7iqwPToV2UUtTDDemq69P8E+WJ4n5W7Iln3pgK+32y19B4oT5q"
// + "iUwXbbEaAXPPZFmT5svPH6XxiQgsiaeZtwQjY61qDga6UH2mYGp0GbrP3i9TjPNt"
// + "IeSwUSaH2YZfwNgFWqj+y/0jjl8DUsN2tIFVSNpNTZNQ/VX4Dln0Z5DBPK1mSskd"
// + "N6uPUj9Ga/IKnwUIv+wL1VWjLNlUjcEHsUE+YE2FN03VnWDJ/VHs7UdHha4d/nUH"
// + "rZrJsKkauqnwJsYbijQU+a0HubwXB7BYMlKovikwNpdMS3+lBzjS5KIu6mRv1GoE"
// + "vQIDAQAB";
//
// //服务器私钥(经过pkcs8格式处理)
// private static final String serverPrvKeyPkcs8 = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDoPD2fCMGYMP8J"
// + "rVCdEbIaO0tsXgJfYQYZLuKrA9OhXZRS1MMN6arr0/wT5YniflbsiWfemAr7fbLX"
// + "0HihPmqJTBdtsRoBc89kWZPmy88fpfGJCCyJp5m3BCNjrWoOBrpQfaZganQZus/e"
// + "L1OM820h5LBRJofZhl/A2AVaqP7L/SOOXwNSw3a0gVVI2k1Nk1D9VfgOWfRnkME8"
// + "rWZKyR03q49SP0Zr8gqfBQi/7AvVVaMs2VSNwQexQT5gTYU3TdWdYMn9UeztR0eF"
// + "rh3+dQetmsmwqRq6qfAmxhuKNBT5rQe5vBcHsFgyUqi+KTA2l0xLf6UHONLkoi7q"
// + "ZG/UagS9AgMBAAECggEBANP72QvIBF8Vqld8+q7FLlu/cDN1BJlniReHsqQEFDOh"
// + "pfiN+ZZDix9FGz5WMiyqwlGbg1KuWqgBrzRMOTCGNt0oteIM3P4iZlblZZoww9nR"
// + "sc4xxeXJNQjYIC2mZ75x6bP7Xdl4ko3B9miLrqpksWNUypTopOysOc9f4FNHG326"
// + "0EMazVaXRCAIapTlcUpcwuRB1HT4N6iKL5Mzk3bzafLxfxbGCgTYiRQNeRyhXOnD"
// + "eJox64b5QkFjKn2G66B5RFZIQ+V+rOGsQElAMbW95jl0VoxUs6p5aNEe6jTgRzAT"
// + "kqM2v8As0GWi6yogQlsnR0WBn1ztggXTghQs2iDZ0YkCgYEA/LzC5Q8T15K2bM/N"
// + "K3ghIDBclB++Lw/xK1eONTXN+pBBqVQETtF3wxy6PiLV6PpJT/JIP27Q9VbtM9UF"
// + "3lepW6Z03VLqEVZo0fdVVyp8oHqv3I8Vo4JFPBDVxFiezygca/drtGMoce0wLWqu"
// + "bXlUmQlj+PTbXJMz4VTXuPl1cesCgYEA6zu5k1DsfPolcr3y7K9XpzkwBrT/L7LE"
// + "EiUGYIvgAkiIta2NDO/BIPdsq6OfkMdycAwkWFiGrJ7/VgU+hffIZwjZesr4HQuC"
// + "0APsqtUrk2yx+f33ZbrS39gcm/STDkVepeo1dsk2DMp7iCaxttYtMuqz3BNEwfRS"
// + "kIyKujP5kfcCgYEA1N2vUPm3/pNFLrR+26PcUp4o+2EY785/k7+0uMBOckFZ7GIl"
// + "FrV6J01k17zDaeyUHs+zZinRuTGzqzo6LSCsNdMnDtos5tleg6nLqRTRzuBGin/A"
// + "++xWn9aWFT+G0ne4KH9FqbLyd7IMJ9R4gR/1zseH+kFRGNGqmpi48MS61G0CgYBc"
// + "PBniwotH4cmHOSWkWohTAGBtcNDSghTRTIU4m//kxU4ddoRk+ylN5NZOYqTxXtLn"
// + "Tkt9/JAp5VoW/41peCOzCsxDkoxAzz+mkrNctKMWdjs+268Cy4Nd09475GU45khb"
// + "Y/88qV6xGz/evdVW7JniahbGByQhrMwm84R9yF1mNwKBgCIJZOFp9xV2997IY83S"
// + "habB/YSFbfZyojV+VFBRl4uc6OCpXdtSYzmsaRcMjN6Ikn7Mb9zgRHR8mPmtbVfj"
// + "B8W6V1H2KOPfn/LAM7Z0qw0MW4jimBhfhn4HY30AQ6GeImb2OqOuh3RBbeuuD+7m"
// + "LpFZC9zGggf9RK3PfqKeq30q";
//服务器公钥
private static final String serverPubKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvjK6D4d5lAC83QLQ6wFQ\n" +
"XQx+fza9CTuPSPzMFkJeA39kI6NucmyaacAiNumqm3BDI0Uc6Sl8bZ0hoaHDCNBw\n" +
"SHNhlixN3PiKktr87dV+QVVdEaeCK6zVE6qe/Sq1g3bj7sOG9JjTAhBHSR2CcsXr\n" +
"A/3JHC1gnrQjAH7sNEbOACgyr9xSR48LURoz1oeEudrVlU+537gbgijSuQ4keSZ2\n" +
"d4UW6JfcqSJG+Sywp2mHIQVBPhu29xbHbXe756VB9U4b5zGZ15nWUONYYBgI5hfl\n" +
"RY6TOOeWxsqJfUy5+hyh+x8ku9/4RdKhotfVGsugry+ItwaWePFr726tV+bEi5d4\n" +
"CwIDAQAB";
//服务器私钥(经过pkcs8格式处理)
private static final String serverPrvKeyPkcs8 = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+MroPh3mUALzd\n" +
"AtDrAVBdDH5/Nr0JO49I/MwWQl4Df2Qjo25ybJppwCI26aqbcEMjRRzpKXxtnSGh\n" +
"ocMI0HBIc2GWLE3c+IqS2vzt1X5BVV0Rp4IrrNUTqp79KrWDduPuw4b0mNMCEEdJ\n" +
"HYJyxesD/ckcLWCetCMAfuw0Rs4AKDKv3FJHjwtRGjPWh4S52tWVT7nfuBuCKNK5\n" +
"DiR5JnZ3hRbol9ypIkb5LLCnaYchBUE+G7b3Fsdtd7vnpUH1ThvnMZnXmdZQ41hg\n" +
"GAjmF+VFjpM455bGyol9TLn6HKH7HyS73/hF0qGi19Uay6CvL4i3BpZ48Wvvbq1X\n" +
"5sSLl3gLAgMBAAECggEAAj2Ou4gZAolPsDrMQzhsvevbwZvfdjBha7auoMR/XwMt\n" +
"Js5SCr8EwqIkxQjTnakg4VV7FbQLZy8mqkTBi2UJLZFOYPp8oFG9MCWsPRD6v8JF\n" +
"qmOSwPj0OZsU7F6IbNgFr1ZWTKNQOQIAFPhoBPoX3qAqsk5GiRgOIX9dQPBklNPf\n" +
"L7e0xQw0uYxqHHt4ugv7GzGIbjC8uLetf9hyznY94JJWjr4AsW/LOojXHZ0Zmkl1\n" +
"lFswTnRRK7ddp4x1LrA63sp7j1Wl2K+J+NRM49zEoZBG0CmTA4itM7p0XrjEmnmI\n" +
"AwgnxLp2iasvuxCiCxnnu4I+53Ve1FSc5eSMlK+jwQKBgQDqV78LUOjNsuuDuzS9\n" +
"97yfWZUWi2M8btnUdtG2jirw4DKD1ds2WgLxqBE/LrEgAeqQ53vnXZyGGR9HH8s3\n" +
"bi6TxTXrZPkEj2dzP8fpa4d5eUFQrKkp/91tqUVGrks3tYQbJ39JAetr9eKgNNBc\n" +
"85/U6DPXJi0x7jtj9yUdO1cYIwKBgQDPxpMq28weh0Fe5b3Q3b0AH6mE6dSRqQ/q\n" +
"hTzgWg36tcJIb2aeiVLX3FvkDojpUH43CBxGbtM//fMxfjKrTvHqnORaR8g4cXBm\n" +
"/mYaHn2v/7s6cZY9/BX73Bn82rHOAUAEFk/Ww9OOgJ0y00p7h9kK4hBKCGVKryWd\n" +
"cDGUVXvq+QKBgQDoJbLJKAboN3XeUuclxbSi+2CZK85MANhkBK0tttrNMpx4Q7Pc\n" +
"vQCrmr4zJDMtrRhNIjR5eB/mLB7zG4j6SXl0w+ntXmLd5J4r6qRFFVPov3k3zUPr\n" +
"qmAWEZjiMymqb3QGXnNWxMMOeVBfOtKrMmFEzh8E5Pniu8kz95JZyf42lwKBgBT8\n" +
"DkMG3e+7Y1vNQkWFD6CikgFtiF2JwKTD/ij+j2jh0JR2Q9wBLI/GnrVCzosZ6RVv\n" +
"yUNH0CgnYtd90mpA1+gFHn8LvuoMcvjD+tXqfHE5F9TIQg9SlXnRegJyqACRWcDP\n" +
"7BJZxtUeokHO2zfsuXwC5vhDLs/DLr5e5XMAyzopAoGAPQBelY71QmGfTHRWWGjW\n" +
"hvBZ2yrvs1as/sXnHgu7SReBXx93b09e0sK66Fmi/Uh9NqZYSE/DrsSYfsLDBzme\n" +
"5dzuCyD7WLnQCYOP6ok5DNykCGYpt01IzCNoE1Sz8evV3a++bhvlgFHdij/OVear\n" +
"O2yF1NtmiWpr4eZ1uxsrgTg=";
public static String getServerPubKey() {
return serverPubKey;
}
public static String getServerPrvKeyPkcs8() {
return serverPrvKeyPkcs8;
}
}
创建filters包,创建RSARequestFilter类
package com.tensquare.encrypt.filters;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.http.HttpServletRequestWrapper;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import com.tensquare.encrypt.rsa.RsaKeys;
import com.tensquare.encrypt.service.RsaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import javax.servlet.ServletInputStream;
@Component
public class RSARequestFilter extends ZuulFilter {
@Autowired
private RsaService rsaService;
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
@Override
public int filterOrder() {
return FilterConstants.PRE_DECORATION_FILTER_ORDER+1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run(){
System.out.println("过滤器已经开启!!");
RequestContext ctx = RequestContext.getCurrentContext();
String decryptData = "";
try {
//获取请求的地址
String url = ctx.getRequest().getRequestURI().toString();
//获取请求的流对象
ServletInputStream is = ctx.getRequest().getInputStream();
//获取传递过来的参数
String requestParam = StreamUtils.copyToString(is, Charsets.UTF_8);
//判断参数是否为空
if (!Strings.isNullOrEmpty(requestParam)){
//不为空就将其解密
decryptData = rsaService.RSADecryptDataPEM(requestParam, RsaKeys.getServerPrvKeyPkcs8());
}
//判断解密后内容是否为空
if (!Strings.isNullOrEmpty(decryptData)){
//以json格式写入新的请求
final byte[] bytes = decryptData.getBytes();
ctx.setRequest(new HttpServletRequestWrapper(ctx.getRequest()){
@Override
public ServletInputStream getInputStream(){
return new ServletInputStreamWrapper(bytes);
}
@Override
public int getContentLength() {
return bytes.length;
}
@Override
public long getContentLengthLong() {
return bytes.length;
}
});
}
ctx.addZuulRequestHeader("Content-Type",String.valueOf(MediaType.APPLICATION_JSON)+";charset=UTF-8");
}catch (Exception e){
System.out.println(e);
}
return null;
}
}
将openssl生成的公钥和私钥添加进RsaKeys中
进入RSA官网:RSA官网
下载OpenSSL-Win64版本
然后在mycerts文件夹下打开命令行
输入openssl genrsa -out …/mycerts/rsa_private_key.pem 2048生成私钥
输入openssl rsa -in …/mycerts/rsa_private_key.pem -pubout -out …/mycerts/rsa_public_key_2048.pub生成公钥
输入openssl pkcs8 -topk8 -inform PEM -in …/mycerts/rsa_private_key.pem -outform PEM -nocrypt > …/mycerts/rsa_private_key_pkcs8.pem私钥转换成pkcs8格式
最终以此开启EUreka微服务、网关微服务、自己需要加密的微服务(本文是文章微服务做例子)
(注意:测试的时候地址和网关是网关微服务配置的地址和路径,也就是必须要在原有的controller层的路径上改变端口为9013,路径前面加上article)