加密算法RSA,签名校验算法 SHA1WithRSA 算法,签名后使用BASE64转码 工具类
签名
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Enumeration;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
* rsa私钥解密
* 加签验签
*/
public class RSATest {
private static KeyStore signcertkey;
private static String privatekeydir = "测试证书.pfx";
private static String password = "12312";
private static String charsetname = "UTF-8";
private static String keyrule = "RSA";
private static String algorithm ="SHA1With";
public static void main(String args[]) throws UnsupportedEncodingException, Exception {
byte[] signStr = sign(signText.getBytes(charsetname),getSignPrivateKey().getEncoded(),keyrule,algorithm+keyrule);
System.out.println("签名结果:"+base64.encodeAsString(signStr));
}
/**
* RSA 私钥解密
* @param privateKey 私钥
* @param data 密文
* @param padMode 填充模式
* @return 明文
*/
public static byte[] rsaDecrypt(RSAPrivateKey privateKey, byte[] data) {
if (privateKey == null) {
System.out.println("privateKey is null");
}
String algorithm = "RSA/None/PKCS1Padding";
byte[] res = null;
try {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
res = cipher.doFinal(data);
} catch (Exception e) {
System.out.println("Fail: RSA ecrypt"+e.toString());
}
return res;
}
public static PrivateKey getSignPrivateKey(){
KeyStore ks = getSigncertkey();
try{
Enumeration<String> aliasenum = ks.aliases();
String keyAlias = null;
if (aliasenum.hasMoreElements()) {
keyAlias = aliasenum.nextElement();
}
return (PrivateKey)ks.getKey(keyAlias, password.toCharArray());
}catch(Exception e){
System.out.println("error"+ e.toString());
return null;
}
}
public static synchronized KeyStore getSigncertkey(){
if(signcertkey!=null){
return signcertkey;
}
FileInputStream fis = null;
try {
Security.insertProviderAt(new BouncyCastleProvider(), 1);
Security.addProvider(new BouncyCastleProvider());
signcertkey = KeyStore.getInstance("PKCS12","BC");
fis = new FileInputStream(privatekeydir);
signcertkey.load(fis, password.toCharArray());
fis.close();
} catch (Exception e) {
System.out.println("error"+ e.toString());
}
finally {
try {
fis.close();
} catch (IOException e) {
System.out.println("error"+ e.toString());
}
}
return signcertkey;
}
/**
* 签名数据
*
* @param data
* @param privateKey
* @param keyAlgorithm
* @param signAlgotithm
* @return
* @throws Exception
*/
public static byte[] sign(byte[] data, byte[] privateKey,
String keyAlgorithm, String signAlgotithm) throws Exception {
// 转换私钥材料
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
// 实例化密钥工厂
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm,
SecurityProvider.getProvierName());
// 取私钥匙对象
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 实例化Signature
Signature signature = Signature.getInstance(signAlgotithm,
SecurityProvider.getProvierName());
// 初始化Signature
signature.initSign(priKey);
// 更新
signature.update(data);
// 签名
return signature.sign();
}
/**
* 校验
* @param data 待校验数据
* @param publicKey 公钥
* @param sign 数字签名
* @return boolean 校验成功返回true 失败返回false
* @throws Exception
*
*/
public static boolean verify(byte[] data, byte[] publicKey, byte[] sign,
String keyAlgorithm, String signAlgotithm) throws Exception {
// 转换公钥材料
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
// 实例化密钥工厂
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm,
SecurityProvider.getProvierName());
// 生成公钥
PublicKey pubKey = keyFactory.generatePublic(keySpec);
// 实例化Signature
Signature signature = Signature.getInstance(signAlgotithm,
SecurityProvider.getProvierName());
// 初始化Signature
signature.initVerify(pubKey);
// 更新
signature.update(data);
// 验证
return signature.verify(sign);
}
}
AES加密工具类
import java.security.InvalidKeyException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* AES工具类
*
* @author homax
*
*/
public class AesEncryptUtil {
public final static String UTF_8 = "UTF-8";
public static void main(String[] args) throws Exception{
String sessionKeyStr="pdXezkKvy/Qlo2WK8fH4IiS4awpjfO/yHLG3/SAY658=";
String srcStr ="{\"mobile\":\"18611111111\",\"longitude\":\"100000\",\"latitude\":\"100000\",\"address\":\"北京23市\"}";
String str1=AesEncryptUtil.AES_ECB_encrypt(srcStr, sessionKeyStr);
System.out.println("加密前:"+srcStr);
System.out.println("加密后:"+str1);
String str2=AesEncryptUtil.AES_ECB_decrypt(str1, sessionKeyStr);
System.out.println("解密后:"+str2);
}
/**
* 加密方法
* @param sSrc 被加密内容
* @param sKey 加密key
* @return
* @throws Exception
*/
public static String AES_ECB_encrypt(String sSrc, String sKey,
String encoding) throws Exception {
if (sKey == null) {
return null;
}
byte[] raw =Base64.decodeBase64(sKey);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes(encoding));
return Base64.encodeBase64String(encrypted);
}
public static String AES_ECB_decrypt(String sSrc, String sKey,
String encoding) throws Exception {
if (sKey == null) {
return null;
}
// byte[] raw = sKey.getBytes();
byte[] raw =Base64.decodeBase64(sKey);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = Base64.decodeBase64(sSrc);
byte[] original = cipher.doFinal(encrypted1);
return new String(original, encoding);
}
public static String AES_ECB_encrypt(String sSrc, String sKey) throws Exception {
return AES_ECB_encrypt(sSrc, sKey,UTF_8);
}
public static String AES_ECB_decrypt(String sSrc, String sKey) throws Exception {
return AES_ECB_decrypt(sSrc,sKey,UTF_8);
}
/**
* 加密方法
* @param sSrc 被加密内容
* @param sKey 加密key
* @return
* @throws Exception
*/
public static String AES_CBC_encrypt(String sSrc, String sKey)
throws Exception {
if (sKey == null) {
return null;
}
if (sKey.length() != 16) {
throw new InvalidKeyException("The key's length must be 16");
}
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("Xadiapdfaxi0s91D".getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes(UTF_8));
return Base64.encodeBase64String(encrypted);
}
/**
* 解密方法
*
* @param sSrc
* 被解密内容
* @param sKey
* 解密key
* @return
* @throws Exception
*/
public static String AES_CBC_decrypt(String sSrc, String sKey)
throws Exception {
try {
if (sKey == null) {
return null;
}
if (sKey.length() != 16) {
return null;
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(
"Xadiapdfaxi0s91D".getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
// byte[] encrypted1 = new Base64().decode(sSrc);
byte[] encrypted1 = Base64.decodeBase64(sSrc);
try {
byte[] original = cipher.doFinal(encrypted1);
return new String(original, UTF_8);
} catch (Exception e) {
return null;
}
} catch (Exception ex) {
return null;
}
}
}
import java.security.Security;
public class SecurityProvider {
private static String PROVIDER_NAME="BC";
private static boolean ISDECIDE=false;
public static String getProvierName(){
if (ISDECIDE && Security.getProvider(PROVIDER_NAME)!=null){
return PROVIDER_NAME;
}else{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
ISDECIDE=true;
return PROVIDER_NAME;
}
}
}
记录一下,以备后忘