加密解密

parent 185b03f0
......@@ -12,6 +12,8 @@ import cn.quantgroup.xyqb.service.user.IUserQueryLogService;
import cn.quantgroup.xyqb.util.IdcardValidator;
import cn.quantgroup.xyqb.util.ValidationUtil;
import cn.quantgroup.xyqb.util.encrypt.RSA;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -59,21 +61,28 @@ public class UserQueryLogController {
@Autowired
private IHttpService httpService;
private static final String="publicKey=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYiw1PKWnCbkKyzHK+blHpKTR/qtO3Oq7nvjSdcopCSmOJqji3B+qJMrf03242mYJIQeF3YSTQZTfri5EkNgoqn0Y/KYpLAKuq89jPdIkB3lvirvew9tpfbAT4B14WgoWdMH5ooqBt0ly3f+JjoBM5dKFTOrhckhFDoaB3UAaaiQIDAQAB";
@RequestMapping("/queryLog")
public JsonResult queryLog(@RequestParam(required=false) String beginDate,@RequestParam(required=false) String endDate, Integer pageId, Integer pageSize) {
try{
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sfs=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1=null,date2=null;
if(beginDate!=null&& StringUtils.hasLength(beginDate)){
date1=sf.parse(beginDate);
date1=sfs.parse(beginDate+" 00:00:00");
}else{
date1=new Date();
String nowStr=sf.format(new Date());
date1=sfs.parse(nowStr+" 00:00:00");
//date1=new Date();
}
if(endDate!=null&& StringUtils.hasLength(endDate)){
date2=sf.parse(endDate);
date2=sfs.parse(endDate+" 23:59:59");
}else{
date2=new Date();
String nowEndStr=sf.format(new Date());
date2=sfs.parse(nowEndStr+" 23:59:59");
}
List<UserQueryLog> userQueryLogs=userQueryLogService.findByTimestamp(date1,date2,pageId-1,pageSize);
......@@ -206,30 +215,20 @@ public class UserQueryLogController {
return JsonResult.buildSuccessResult("查询成功",uqi);
}
private String getBankCardsByPhoneNos(String phoneNo){
// HashMap<String, String> parameters = new HashMap<>();
// parameters.put("phoneNo", phoneNo);
// parameters.put("merchantId", payCenterId);
// //访问用户中心查询用户银行卡接口
// String resultStr = httpService.post(payCenterUrl + "ex/common_bank_card/list", parameters);
// StringBuffer cardList=null;
// try{
// JsonObject obj = new JsonParser().parse(resultStr).getAsJsonObject();
// if(obj.get("data")!=null){
// JsonArray array = obj.get("data").getAsJsonArray();
// for(JsonElement jsonElement : array){
// JsonObject jo = jsonElement.getAsJsonObject();
// String cardNo=jo.get("cardNo").getAsString();
// cardList.append(cardNo+",");
// }
// }
//
// }catch(Exception e){
//
// }
// return cardList.toString();
return null;
private String getBankCardsByPhoneNos(List<String> phoneNos){
String phoneNoStr= JSON.toJSONString(phoneNos);
RSA.encrypt(phoneNoStr,);
HashMap<String, String> parameters = new HashMap<>();
parameters.put("data", "");
parameters.put("sign", "");
//访问用户中心查询用户银行卡接口
String resultStr = httpService.post(payCenterUrl + "/ex/search/card_list", parameters);
StringBuffer cardList=null;
return cardList.toString();
}
@RequestMapping("/exportUserInfo")
......
This diff is collapsed.
package cn.quantgroup.xyqb.util.encrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by tums on 2015/11/30.
*/
public final class MD5Util {
private static final Logger LOGGER = LoggerFactory.getLogger(MD5Util.class);
public static String build(String content) {
MessageDigest messageDigest;
try {
messageDigest = MessageDigest
.getInstance("md5");
} catch (NoSuchAlgorithmException e) {
LOGGER.error(e.getMessage(), e);
return null;
}
messageDigest.update(content.getBytes());
byte[] domain = messageDigest.digest();
StringBuilder md5StrBuff = new StringBuilder();
// converting domain to String
for (int i = 0; i < domain.length; i++) {
if (Integer.toHexString(0xFF & domain[i]).length() == 1) {
md5StrBuff.append("0").append(
Integer.toHexString(0xFF & domain[i]));
} else
md5StrBuff.append(Integer.toHexString(0xFF & domain[i]));
}
return md5StrBuff.toString();
}
}
package cn.quantgroup.xyqb.util.encrypt;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class RSA {
/**
* 指定key的大小
*/
private static int KEYSIZE = 1024;
public static final String CHAR_ENCODING = "UTF-8";
public static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";
/** *//**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/** *//**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* 生成密钥对
*/
public static Map<String, String> generateKeyPair() throws Exception {
/** RSA算法要求有一个可信任的随机数源 */
SecureRandom sr = new SecureRandom();
/** 为RSA算法创建一个KeyPairGenerator对象 */
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
/** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
kpg.initialize(KEYSIZE, sr);
/** 生成密匙对 */
KeyPair kp = kpg.generateKeyPair();
/** 得到公钥 */
Key publicKey = kp.getPublic();
byte[] publicKeyBytes = publicKey.getEncoded();
String pub = new String(Base64.encodeBase64(publicKeyBytes),
CHAR_ENCODING);
/** 得到私钥 */
Key privateKey = kp.getPrivate();
byte[] privateKeyBytes = privateKey.getEncoded();
String pri = new String(Base64.encodeBase64(privateKeyBytes),
CHAR_ENCODING);
Map<String, String> map = new HashMap<String, String>();
map.put("publicKey", pub);
map.put("privateKey", pri);
RSAPublicKey rsp = (RSAPublicKey) kp.getPublic();
BigInteger bint = rsp.getModulus();
byte[] b = bint.toByteArray();
byte[] deBase64Value = Base64.encodeBase64(b);
String retValue = new String(deBase64Value);
map.put("modulus", retValue);
return map;
}
/**
* 加密方法 source: 源数据
*/
public static String encrypt(String source, String publicKey)
throws Exception {
Key key = getPublicKey(publicKey);
/** 得到Cipher对象来实现对源数据的RSA加密 */
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] b = source.getBytes();
/** 执行加密操作 */
int inputLen = b.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(b, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(b, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] b1 = out.toByteArray();
out.close();
return new String(Base64.encodeBase64(b1), CHAR_ENCODING);
}
/**
* 解密算法 cryptograph:密文
*/
public static String decrypt(String cryptograph, String privateKey)
throws Exception {
Key key = getPrivateKey(privateKey);
/** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] b1 = Base64.decodeBase64(cryptograph.getBytes());
int inputLen = b1.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(b1, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(b1, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] b = out.toByteArray();
out.close();
/** 执行解密操作 */
return new String(b);
}
/**
* 得到公钥
*
* @param key 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
Base64.decodeBase64(key.getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 得到私钥
*
* @param key 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(
Base64.decodeBase64(key.getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
public static String sign(String content, String privateKey) {
String charset = CHAR_ENCODING;
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
Base64.decodeBase64(privateKey.getBytes()));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return new String(Base64.encodeBase64(signed));
} catch (Exception e) {
}
return null;
}
public static boolean checkSign(String content, String sign, String publicKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode2(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
Signature signature = Signature
.getInstance("SHA1WithRSA");
signature.initVerify(pubKey);
signature.update(content.getBytes("utf-8"));
boolean bverify = signature.verify(Base64.decode2(sign));
return bverify;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment