java RSA加密 RSA签名

package com.feng.util;


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.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;


import javax.crypto.Cipher;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class RSAUtil {

/**
* 生成Base64密钥对
* @return
*/
public static Map<String, String> geneKeyPairs() {
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
keyPairGen.initialize(512);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey pubKey = (RSAPublicKey)keyPair.getPublic();
RSAPrivateKey priKey = (RSAPrivateKey)keyPair.getPrivate();
Map<String, String> map = new HashMap<String, String>();
BASE64Encoder encode = new BASE64Encoder();
byte[] pub = pubKey.getEncoded();
byte[] pri = priKey.getEncoded();
String pubstr = encode.encode(pub);
String pristr = encode.encode(pri);
System.out.println(pubstr);
System.out.println(pristr);
map.put("pubKey", pubstr);
map.put("priKey", pristr);
return map;
}

/**
* 根据base64字符串初始化公钥
* @param pubKeyStr
* @return
* @throws Exception
*/
public static PublicKey strToPubKey(String pubKeyStr) 
throws Exception {
byte[] pubKeyArr = new BASE64Decoder().decodeBuffer(pubKeyStr);
   // 构造PKCS8EncodedKeySpec对象  
   X509EncodedKeySpec pkcs8KeySpec = new X509EncodedKeySpec(pubKeyArr);  
        // KEY_ALGORITHM 指定的加密算法  
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");    
        // 取私钥匙对象  
        PublicKey pubKey = keyFactory.generatePublic(pkcs8KeySpec);
        return pubKey;
}

/**
* 根据base64字符串初始化私钥
* @param priKeyStr
* @return
* @throws Exception
*/
public static PrivateKey strToPriKey(String priKeyStr) 
throws Exception {
        byte[] priKeyArr = new BASE64Decoder().decodeBuffer(priKeyStr);  
        // 取得私钥  
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKeyArr);  
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);  
        return priKey;
}

/**
*  公钥加密数据
* @param data
* @param pubKeyStr
* @return
*/
public static String pubKeyEncrypt(String data ,String pubKeyStr) {
byte[] dataArr = data.getBytes();
PublicKey pubKey = null;
try {
pubKey = strToPubKey(pubKeyStr);
} catch (Exception e) {
e.printStackTrace();
}
// 用公钥对数据加密  
byte[] dataEnc = null;
try {
Cipher cipher = Cipher.getInstance(KeyFactory.
getInstance("RSA").getAlgorithm());  
cipher.init(Cipher.ENCRYPT_MODE, pubKey);  
   dataEnc = cipher.doFinal(dataArr);
} catch (Exception e) {
e.printStackTrace();
}
        return  new BASE64Encoder().encode(dataEnc);
}

/**
* 私钥解密数据
* @param dataEnc
* @param priKeyStr
* @return
*/
public static String priKeyDeco(String dataEnc, String priKeyStr) {
byte[] dataArr = null;
PrivateKey priKey = null;
try {
dataArr = new BASE64Decoder().decodeBuffer(dataEnc);
priKey = strToPriKey(priKeyStr);
} catch (Exception e) {
e.printStackTrace();
}
// 用私钥解密数据 
byte[] dataEnced = null;
try {
Cipher cipher = Cipher.getInstance(KeyFactory.
getInstance("RSA").getAlgorithm());  
cipher.init(Cipher.DECRYPT_MODE, priKey);  
dataEnced = cipher.doFinal(dataArr);
} catch (Exception e) {
e.printStackTrace();
}
        return  new String(dataEnced);
}

/**
* 私钥生成签名
* @param data
* @param priKeyStr
* @return
*/
public static String priKeyGenSign(String data, String priKeyStr) {
byte[] dataByte = data.getBytes();
PrivateKey priKey = null;
try {
priKey = strToPriKey(priKeyStr);
} catch (Exception e) {
e.printStackTrace();
}
// 用私钥生成签名 
byte[] dataSign = null;
try {
Signature signature = Signature.getInstance("MD5withRSA");  
       signature.initSign(priKey);  
       signature.update(dataByte);  
       dataSign = signature.sign();
} catch (Exception e) {
e.printStackTrace();
}
        return  new BASE64Encoder().encode(dataSign);
}

/**
* 公钥验证签名
* @param data
* @param sign
* @param pubKeyStr
* @return
*/
public static boolean pubKeyVerSign(String data, String sign ,String pubKeyStr) {
byte[] signArr = null;
PublicKey pubKey = null;
byte[] dataByte = data.getBytes();
try {
pubKey = strToPubKey(pubKeyStr);
signArr = new BASE64Decoder().decodeBuffer(sign);
} catch (Exception e) {
e.printStackTrace();
}
Signature signature = null; 
boolean flag = false;
try {
   signature = Signature.getInstance("MD5withRSA");  
signature.initVerify(pubKey);  
      signature.update(dataByte); 
      flag = signature.verify(signArr);
} catch (Exception e) {
e.printStackTrace();
}  
   // 验证签名是否正常  
   return flag;
}


}

测试类


@Test
public void testRSA(){
String info = "冯立业feng123456";
System.out.println("加密前:"+info);
String pubKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAI4FZPiLCo+PX+IpWC5dLnAUvq7fbnlRCOyneoAB4ozW"+
   "Hm0KYoWTpPrS3PC3G5evHlYhjh60yhVY5e+9Nkc49uMCAwEAAQ==";
String priKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAjgVk+IsKj49f4ilYLl0ucBS+rt9u"+
"eVEI7Kd6gAHijNYebQpihZOk+tLc8Lcbl68eViGOHrTKFVjl7702Rzj24wIDAQABAkBO6RRnPOpL"+
"RgCiqxJCAKhSwlQI2kCJy8rHo27fPSzhzyorrfhRpAdHLx9Wf3Tejv3OF47pPNtaQv5eUCkf9lTh"+
"AiEA0KqYNO3Z61tOJwaaBayniqhalKg37WsZ5a8Q/+bHjKkCIQCuPKi7ooWDC7KAh4P/wjLlEU1Y"+
"B0GtVFV3HHL2Pu0yqwIgGM5e/9PS1z7ogI0xXEFVPY+cDRYeZ/QWhQ6V18YorNkCIQCShAPHtQTc"+
"i8uQ9WP0gBNYONJ3QbLi1FYCEXRCyeugfQIhAJJheiyn0kAuRLMRME1dOoyHPGG339frfQmn/+K9"+
"Xf93";
String infoEnc = RSAUtil.pubKeyEncrypt(info, pubKey);
System.out.println("加密后:"+infoEnc);
String infoDec = RSAUtil.priKeyDeco(infoEnc, priKey);
       System.out.println("加密后:"+infoDec);
       String sign = RSAUtil.priKeyGenSign(info, priKey);
       System.out.println("签名:" +sign);
       System.out.println("验签:"+RSAUtil.pubKeyVerSign(info, sign, pubKey));
}

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值