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));
}

1、数字签名原理 用RSA算法做数字签名,总的来说,就是签名者用私钥参数d加密,也就是签名;验证者用签字者的公钥参数e解密来完成认证。 下面简要描述数字签名和认证的过程。 (1)、生成密钥 为用户随机生成一对密钥:公钥(e,n)和私钥(d,n). (2)、签名过程 a) 计算消息的散列值H(M). b) 用私钥(d,n)加密散列值:s=(H(M)) mod n,签名结果就是s. c) 发送消息和签名(M,s). (3)、认证过程 a) 取得发送方的公钥(e,n). b) 解密签名s:h=s mod n. c) 计算消息的散列值H(M). d) 比较,如果h=H(M),表示签名有效;否则,签名无效。 根据上面的过程,我们可以得到RSA数字签名的框图如图2-1: 图 2-1 RSA数字签名框图 2、 假设Alice想和Bob通信,以本地两个文件夹Alice和Bob模拟两个用户,实现消息M和签名的模拟分发 (1)、Alice通过RSA算法生成一对密钥:公钥(e,n)和私钥(d,n),将公私钥分别存入pubKey.txt和priKey.txt中。 pubKey.txt中公钥如下: priKey.txt中私钥如下: (2)、将Alice中的pubKey.txt拷到Bob中,模拟公玥的分发。 (3)、将Alice中的消息info.txt做散列,将散列后的值存入hashInfo.txt中。 (4)、将Alice中的消息hashInfo.txt和签名sign.txt拷到Bob中,实现M密文状态下的签名与模拟分发、消息传递。 (5)Bob取得公钥pubKey.txt,用公钥解密签名,计算消息的散列值H(M).比较,如果h=H(M),表示签名有效;否则,签名无效。 后台运行结果如下:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值