欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RSA生成公钥和私钥对

程序员文章站 2024-03-14 15:04:28
...

1、工具类:

package com.util;
import java.io.UnsupportedEncodingException;
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.spec.PKCS8EncodedKeySpec;  
import java.security.spec.X509EncodedKeySpec;  
import java.text.SimpleDateFormat;
import com.core.flow.util.Base64Utils;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;  
import java.util.logging.Level;  
import java.util.logging.Logger;  
  
public class RSAHelper {  
    public static final String KEY_ALGORITHM = "RSA";  
    public static final String PUBLIC_KEY = "PublicKey";  
    public static final String PRIVATE_KEY = "PrivateKey";  
    private static final String SIGNATURE_ALGORITHM = "MD5withRSA";  
  
    public RSAHelper() {  
    }  
  /**
   * 
   * @param keyMap
   * 获取公私钥对
 * @return 
 * @throws Exception 
 * @throws UnsupportedEncodingException 
   * 
   */
    public static Map generateKeyPair() throws Exception{  
        boolean result = false;  
        Map keyMap = new HashMap() ;
        KeyPairGenerator keyPairGenerator = null;  
        try {  
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");  
            result = true;  
        } catch (NoSuchAlgorithmException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null,  
                    ex);  
        }  
  
        if (result) {  
            SecureRandom secureRandom = new SecureRandom();  
  
            String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmssSSS")  
                    .format(new Date());  
            secureRandom.setSeed(currentDateTime.getBytes());  
  
            keyPairGenerator.initialize(1024, secureRandom);  
  
            KeyPair keyPair = keyPairGenerator.genKeyPair();  
  
            PublicKey publicKey = keyPair.getPublic();  
            PrivateKey privateKey = keyPair.getPrivate();  
  
            keyMap.put(RSAHelper.PUBLIC_KEY,Base64Utils.encode(publicKey.getEncoded()));
            keyMap.put(RSAHelper.PRIVATE_KEY, Base64Utils.encode(privateKey.getEncoded()));  
            
            return keyMap;
        }
		return keyMap;  
    }  
  
  /**
   * 
   * @param strData 源数据字符串
   * @param strPrivateKeyBytes  签名私钥
   * @return String
   * 通过私钥签名
 * @throws Exception 
   */
    public static String sign(String strData,   String strPrivateKeyBytes) throws Exception {  
        byte[] signedData = null;  
        
        byte[] privateKeyBytes =Base64Utils.decode(strPrivateKeyBytes);
        try {  
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(  
                    privateKeyBytes);  
  
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
  
            PrivateKey privateKey = keyFactory  
                    .generatePrivate(pkcs8EncodedKeySpec);  
  
            Signature signature = Signature.getInstance(RSAHelper.SIGNATURE_ALGORITHM);  
  
            signature.initSign(privateKey);  
            byte[] data = strData.getBytes();
            
            signature.update(data);  
  
            signedData = signature.sign();  
        } catch (Exception ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null,  
                    ex);  
        }  
  
        return Base64Utils.encode(signedData);
    }  
    
    /**
     * 
     * @param strData            数据明文串
     * @param strPublicKeyBytes  验签公钥
     * @param strDataSignature   签名数据
     * @return boolean
     * 通过公钥验签
     * @throws Exception 
     * 
     */
    public static boolean verify(String strData,   
           String strPublicKeyBytes, String strDataSignature) throws Exception {  
        boolean result = false; 
        byte[] publicKeyBytes =Base64Utils.decode(strPublicKeyBytes);
        try {  
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(  
                    publicKeyBytes);  
  
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
  
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);  
  
            Signature signature = Signature.getInstance(RSAHelper.SIGNATURE_ALGORITHM);  
  
            signature.initVerify(publicKey);  
            byte[] data = strData.getBytes();
            signature.update(data);  
            byte[] dataSignature =Base64Utils.decode(strDataSignature);
            result = signature.verify(dataSignature);  
        } catch (Exception ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null,  
                    ex);  
        }  
  
        return result;  
    }  
}  

2、测试类:

package com.core.flow.util;
import java.util.Map;
public class RsaTest {
	
	public static void main(String args[]) throws Exception{
		
		//待签名数据
		String strData = "这是一个测试数据,这是一个测试数据,这是一个测试数据。重要的事情说三遍";
		
		//生成公私**对
		Map keyMap = RSAHelper.generateKeyPair();		
		System.out.println("公钥:"+ (String) keyMap.get(RSAHelper.PUBLIC_KEY));
        System.out.println("私钥:"+ (String) keyMap.get(RSAHelper.PRIVATE_KEY));
	   
		//数据签名
		String signData = RSAHelper.sign(strData, (String)keyMap.get(RSAHelper.PRIVATE_KEY));
		//签名数据
		System.out.println(signData); 
		//验签
		boolean b = RSAHelper.verify(strData, (String)keyMap.get(RSAHelper.PUBLIC_KEY), signData);
		//验签结果
		System.out.println(b);
	}
}

有问题可以给我留言哦!!!

 

 

 

 

 

相关标签: RSA加密方式