加密解密
package com.suning.epps.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.Key;
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.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.commons.net.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RSAUtil
{
private static final Logger LOG = LoggerFactory.getLogger(RSAUtil.class);
private static final String RSA = "RSA";
private static final int RSA_SIZE_2048 = 2048;
private static final int RSA_SIZE_1024 = 1024;
private static final String MD5_WITH_RSA = "MD5withRSA";
private static final String SHA1_WITH_RSA = "SHA1WithRSA";
public static final String PUBLIC_KEY = "publicKey";
public static final String PUBLIC_KEY_B64 = "publicKeyBase64";
public static final String PRIVATE_KEY = "privateKey";
public static final String PRIVATE_KEY_B64 = "privateKeyBase64";
public static Map<String, Object> create1024Key()
{
return createKey(1024);
}
public static Map<String, Object> create2048Key()
{
return createKey(2048);
}
public static Map<String, Object> createKey(int keySize)
{
KeyPairGenerator keyGen = null;
try {
keyGen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
LOG.error("初始化密钥工具异常", e);
return null;
}
keyGen.initialize(keySize, new SecureRandom());
KeyPair key = keyGen.generateKeyPair();
PublicKey pubKey = key.getPublic();
PrivateKey priKey = key.getPrivate();
Map map = new HashMap();
map.put("publicKey", pubKey);
map.put("privateKey", priKey);
map.put("publicKeyBase64", Base64.encodeBase64String(pubKey.getEncoded()));
map.put("privateKeyBase64", Base64.encodeBase64String(priKey.getEncoded()));
return map;
}
public static void createKey(String publicFilePath, String privateFilePath, int keySize)
{
try
{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(keySize, new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
write(publicFilePath, pair.getPublic());
write(privateFilePath, pair.getPrivate());
} catch (Exception e) {
LOG.error("密钥处理异常", e);
}
}
private static void write(String path, Object key)
{
File file = new File(path);
if (!file.getParentFile().exists()) {
boolean creat = file.getParentFile().mkdirs();
if (!creat) {
System.out.println("创建文件目录异常!");
return;
}
}
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(path));
oos.writeObject(key);
if (null != oos)
try {
oos.close();
} catch (IOException e) {
oos = null;
}
}
catch (Exception e)
{
LOG.error("密钥写入异常", e);
if (null != oos)
try {
oos.close();
} catch (IOException ee) {
oos = null;
}
}
finally
{
if (null != oos)
try {
oos.close();
} catch (IOException e) {
oos = null;
}
}
}
public static boolean vertiy(byte[] data, byte[] sign, PublicKey pubk)
throws NoSuchAlgorithmException, InvalidKeyException, SignatureException
{
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initVerify(pubk);
signature.update(data);
return signature.verify(sign);
}
public static boolean vertiy(String data, String sign, PublicKey pubk)
throws InvalidKeyException, NoSuchAlgorithmException, SignatureException
{
return vertiy(data.getBytes(), Base64.decodeBase64(sign), pubk);
}
public static byte[] sign(byte[] data, PrivateKey prik)
throws NoSuchAlgorithmException, InvalidKeyException, SignatureException
{
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initSign(prik);
signature.update(data);
return signature.sign();
}
public static String sign(String data, PrivateKey prik)
throws InvalidKeyException, NoSuchAlgorithmException, SignatureException
{
return Base64.encodeBase64URLSafeString(sign(data.getBytes(), prik)).trim();
}
public static PublicKey getPublicKey(String strPubKey)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(strPubKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
return pubKey;
}
public static PrivateKey getPrivateKey(String strPriKey)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(strPriKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyFactory.generatePrivate(priKeySpec);
return priKey;
}
public static PublicKey resolvePublicKey(String path)
{
PublicKey pubkey = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = FileUtils.openInputStream(new File(path));
ois = new ObjectInputStream(fis);
pubkey = (PublicKey)ois.readObject();
return pubkey;
} catch (FileNotFoundException e) {
LOG.error("私钥文件找不到", e);
} catch (IOException e) {
LOG.error("文件输入错误", e);
} catch (ClassNotFoundException e) {
LOG.error("类文件找不到", e);
} catch (Exception e) {
LOG.error("解析异常", e);
} finally {
IOUtils.closeQuietly(ois);
IOUtils.closeQuietly(fis);
}
return null;
}
public static PrivateKey resolvePrivateKey(String path)
{
PrivateKey prikey = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = FileUtils.openInputStream(new File(path));
ois = new ObjectInputStream(fis);
prikey = (PrivateKey)ois.readObject();
return prikey;
} catch (FileNotFoundException e) {
LOG.error("私钥文件找不到", e);
} catch (IOException e) {
LOG.error("文件输入错误", e);
} catch (ClassNotFoundException e) {
LOG.error("类文件找不到", e);
} catch (Exception e) {
LOG.error("解析异常", e);
} finally {
IOUtils.closeQuietly(ois);
IOUtils.closeQuietly(fis);
}
return null;
}
public static String getBase64PublicKeyString(PublicKey pubKey)
{
return Base64.encodeBase64URLSafeString(pubKey.getEncoded()).trim();
}
public static String getBase64PrivateKeyString(PrivateKey priKey)
{
return Base64.encodeBase64URLSafeString(priKey.getEncoded()).trim();
}
public static String getBase64PublicKeyString(String path)
{
PublicKey pubKey = resolvePublicKey(path);
return getBase64PublicKeyString(pubKey);
}
public static String getBase64PrivateKeyString(String path)
{
PrivateKey priKey = resolvePrivateKey(path);
return getBase64PrivateKeyString(priKey);
}
public static String encrypt(Key key, String message)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(1, key);
byte[] miwen = cipher.doFinal(message.getBytes());
return String.valueOf(new BigInteger(miwen));
}
public static String decrypt(Key key, String message)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
byte[] miwen = new BigInteger(message).toByteArray();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(2, key);
byte[] result = cipher.doFinal(miwen);
return new String(result);
}
public static void main(String[] args) throws Exception {
//createKey("D:/RSA/public.key", "D:/RSA/private.key", 1024);
//PublicKey pubKey = resolvePublicKey("D:/RSA/public.key");
//PrivateKey priKey = resolvePrivateKey("D:/RSA/private.key");
//System.out.println("pubKey:" + Base64.encodeBase64URLSafeString(pubKey.getEncoded()));
//System.out.println("priKey:" + Base64.encodeBase64URLSafeString(priKey.getEncoded()));
PublicKey pub = RSAUtil.getPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6MCgSM4a49vOgnGFiNCmGj6aMDcDa+xJQRedD zILy85JBX4nPrEVUxJhl2QWpyVS9/tyUOuXfsujPLnmu1Qsq/3xWz/1+Q+STempO0R0+I4m+CZW8 qNIhMIJJIt2GBOfzUe+HBfF1RZ6eiRp0VSr2c4BOLY8MeCkRPXyrlgTxKwIDAQAB");
PublicKey ebuyPub = RSAUtil.getPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmlcnbcT-nOWsRwCNMdJdCfGhW1WmYRfBJpUJGQRtuQsJRtRqe1XvTzkn7H2z9x4pRyKA7k9R63ZilYBMIUVgaR4zDGOQqb5O8RrWa_8o_obQH8cZ_be0vd0IXni7gDeVjtaU441tuXQdGpUC4BLuLGM4U8TvNLzPiZxlVi3eJ-wIDAQAB");
PrivateKey pri = RSAUtil.getPrivateKey("MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALowKBIzhrj286CcYWI0KYaPpowN wNr7ElBF50PMgvLzkkFfic+sRVTEmGXZBanJVL3+3JQ65d+y6M8uea7VCyr/fFbP/X5D5JN6ak7R HT4jib4Jlbyo0iEwgkki3YYE5/NR74cF8XVFnp6JGnRVKvZzgE4tjwx4KRE9fKuWBPErAgMBAAEC gYBvafvAkIbQzi4RcSKxMkebFwDxlBVQtKdL09jE8G931JszdWkxFYRTamVLpOdHp4uHOihipzAB gbzgpY35OdE4/X5YWPmNdPRjW8TSVSh7LIzTzr2HzsycA81Zmu1q0+c5UP64jOaVx8IbW73sle8j AfH5c8GrvlWPk67IwXXBkQJBAPZs4gxETn8Z5seDhYS0rc66/cPcXTZ6m2YVdJDoqW3k3cchmGWV +JJck8+MCODClkv6K0FChrXtN8KTDm5EXZMCQQDBbBzLSIBPy5fNaN8MlmmqwkfZxaDhBIeVSwo2 sQHKJNF7bLrbZngLLnAuO2dgMxOfRQuZ3YOpzF5grM+vbB0JAkAr86WpvHEnuE3yHeItljA95Boo 2eACPIIFBiShR+4YPK7Vuoc87y/DoyF17isTM4GtEXSvkhcG0cWVPbdgMW9jAkAETxhFHxRcsrhr Bw8RBLjN6Q4Yt+JhoOw0UzujBEZ57mAMU9vFz36VIS+2l/QxnHGvdqZPgzPPsJHZrX/i9JGhAkBA cvLMt0FXwpjuhOVt7ERJSFxsl9Oc11g5zHncLcYaRicc+aVOsr8lkvcn21zKmGI3Ciby6jnuBSG0 840pILit");
String ming = "hellow rsa";
String mi = RSAUtil.encrypt(pub, ming);
System.out.print(mi);
ming = RSAUtil.decrypt(pri,mi);
System.out.print(ming);
Map requestMap = new HashMap();
requestMap.put("responseCode", "0000");
requestMap.put("merchantOrderNos", "20151113000000181|20151113000000182");
//requestMap.put("keyIndex", "13");
requestMap.put("signAlgorithm", "RSA");
requestMap.put("signature", "o5QQ2uB8vq2Tq6aJ660NlDdU5PuyUViD6tefMyqEx90-6VOXaPGOtc8F9nyKU6Fi7lHiSJ_wFGbhBs0yb8qtiz1KbNUv02jNR5r2vtcvRMuBWjxJIWlcxIRFGTVqybPm0oCy6wXj_IYkPumaIWAA6AXDGY1J_NFPq8xDEfMKc0w");
String signature = "o5QQ2uB8vq2Tq6aJ660NlDdU5PuyUViD6tefMyqEx90-6VOXaPGOtc8F9nyKU6Fi7lHiSJ_wFGbhBs0yb8qtiz1KbNUv02jNR5r2vtcvRMuBWjxJIWlcxIRFGTVqybPm0oCy6wXj_IYkPumaIWAA6AXDGY1J_NFPq8xDEfMKc0w";
List<String> excudeKeylist = new ArrayList<String>();
excudeKeylist.add("signature");
excudeKeylist.add("signAlgorithm");
String[] excudeKey = new String[excudeKeylist.size()];
String digest = Digest.digest(requestMap, excudeKeylist.toArray(excudeKey));
boolean rst = RSAUtil.vertiy(digest, signature, ebuyPub);
System.out.print(rst);
}
}
import java.security.*;
import javax.crypto.*;
public class DESEnc {
private static String strDefaultKey = "86b21af7cdef3dc6";
private Cipher encryptCipher = null;
private Cipher decryptCipher = null;
public static String byteArr2HexStr(byte[] arrB) throws Exception {
int iLen = arrB.length;
// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
// 把负数转换为正数
while (intTmp < 0) {
intTmp = intTmp + 256;
}
// 小于0F的数需要在前面补0
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
public static byte[] hexStr2ByteArr(String strIn) throws Exception {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}
public DESEnc() throws Exception {
this(strDefaultKey);
}
public DESEnc(String keyType) throws Exception {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
Key key = getKey(strDefaultKey.getBytes());
encryptCipher = Cipher.getInstance("DES");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher = Cipher.getInstance("DES");
decryptCipher.init(Cipher.DECRYPT_MODE, key);
}
public byte[] encrypt(byte[] arrB) throws Exception {
return encryptCipher.doFinal(arrB);
}
public String encrypt(String strIn) throws Exception {
return byteArr2HexStr(encrypt(strIn.getBytes()));
}
public byte[] decrypt(byte[] arrB) throws Exception {
return decryptCipher.doFinal(arrB);
}
public String decrypt(String strIn) throws Exception {
return new String(decrypt(hexStr2ByteArr(strIn)));
}
private Key getKey(byte[] arrBTmp) throws Exception {
// 创建一个空的8位字节数组(默认值为0)
byte[] arrB = new byte[8];
// 将原始字节数组转换为8位
for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
// 生成密钥
Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
return key;
}
public static void main(String[] args) {
try {
String test = "astest,123456";
DESEnc des = new DESEnc();//默认密钥
System.out.println("加密前的字符:" + test);
System.out.println("加密后的字符:" + des.encrypt(test));
System.out.println("解密后的字符:" + des.decrypt(des.encrypt(test)));
} catch (Exception e) {
e.printStackTrace();
}
}
}