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
    评论
RSA加密签名都是基于RSA算法的,但是加密签名的目的和流程有所不同。 RSA加密流程如下: 1. 选择两个大质数p和q,计算n=p*q,并记为RSA模数。 2. 计算欧拉函数φ(n)=(p-1)*(q-1)。 3. 选择一个整数e,1<e<φ(n),且e与φ(n)互质,e作为公钥指数。 4. 计算d,使得d*e≡1(mod φ(n)),d作为私钥指数。 5. 加密时,对明文m进行加密,计算c=m^e(mod n)。 6. 解密时,对密文c进行解密,计算m=c^d(mod n)。 RSA签名流程如下: 1. 选择两个大质数p和q,计算n=p*q,并记为RSA模数。 2. 计算欧拉函数φ(n)=(p-1)*(q-1)。 3. 选择一个整数e,1<e<φ(n),且e与φ(n)互质,e作为签名者的私钥指数。 4. 计算d,使得d*e≡1(mod φ(n)),d作为签名者的公钥指数。 5. 对消息m进行签名,计算s=m^d(mod n)。 6. 验证签名时,对接收到的消息m和签名s进行验证,计算m'=s^e(mod n),如果m'=m,则验证通过。 下面是Java代码示例: RSA加密: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import javax.crypto.Cipher; public class RSAEncrypt { public static void main(String[] args) throws Exception { String plainText = "Hello, world!"; KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); KeyPair kp = kpg.generateKeyPair(); PublicKey publicKey = kp.getPublic(); PrivateKey privateKey = kp.getPrivate(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedText = cipher.doFinal(plainText.getBytes()); System.out.println("加密后的密文:" + new String(encryptedText)); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedText = cipher.doFinal(encryptedText); System.out.println("解密后的明文:" + new String(decryptedText)); } } ``` RSA签名: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; public class RSASign { public static void main(String[] args) throws Exception { String plainText = "Hello, world!"; KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); KeyPair kp = kpg.generateKeyPair(); PublicKey publicKey = kp.getPublic(); PrivateKey privateKey = kp.getPrivate(); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(privateKey); signature.update(plainText.getBytes()); byte[] signedText = signature.sign(); System.out.println("签名后的内容:" + new String(signedText)); signature.initVerify(publicKey); signature.update(plainText.getBytes()); boolean result = signature.verify(signedText); System.out.println(result ? "验签成功" : "验签失败"); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值