RSA生成公钥和私钥对

 

Base64Utils工具类:

package com.rsa.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.sun.org.apache.xml.internal.security.utils.Base64;

 

/**
 * <p>
 * BASE64编码解码工具包
 * </p>
 * <p> 
 * 依赖javabase64-1.3.1.jar
 * </p>
 * 
 * @author IceWee
 * @date 2012-5-19
 * @version 1.0
 */
public class Base64Utils {

    /**
     * 文件读取缓冲区大小
     */
    private static final int CACHE_SIZE = 1024;
    
    /**
     * <p>
     * BASE64字符串解码为二进制数据
     * </p>
     * 
     * @param base64
     * @return
     * @throws Exception
     */
    public static byte[] decode(String base64) throws Exception {
        return Base64.decode(base64.getBytes());
    }
    
    /**
     * <p>
     * 二进制数据编码为BASE64字符串
     * </p>
     * 
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String encode(byte[] bytes) throws Exception {
        return new String(Base64.encode(bytes));
    }
    
    /**
     * <p>
     * 将文件编码为BASE64字符串
     * </p>
     * <p>
     * 大文件慎用,可能会导致内存溢出
     * </p>
     * 
     * @param filePath 文件绝对路径
     * @return
     * @throws Exception
     */
    public static String encodeFile(String filePath) throws Exception {
        byte[] bytes = fileToByte(filePath);
        return encode(bytes);
    }
    
    /**
     * <p>
     * BASE64字符串转回文件
     * </p>
     * 
     * @param filePath 文件绝对路径
     * @param base64 编码字符串
     * @throws Exception
     */
    public static void decodeToFile(String filePath, String base64) throws Exception {
        byte[] bytes = decode(base64);
        byteArrayToFile(bytes, filePath);
    }
    
    /**
     * <p>
     * 文件转换为二进制数组
     * </p>
     * 
     * @param filePath 文件路径
     * @return
     * @throws Exception
     */
    public static byte[] fileToByte(String filePath) throws Exception {
        byte[] data = new byte[0];
        File file = new File(filePath);
        if (file.exists()) {
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
            byte[] cache = new byte[CACHE_SIZE];
            int nRead = 0;
            while ((nRead = in.read(cache)) != -1) {
                out.write(cache, 0, nRead);
                out.flush();
            }
            out.close();
            in.close();
            data = out.toByteArray();
         }
        return data;
    }
    
    /**
     * <p>
     * 二进制数据写文件
     * </p>
     * 
     * @param bytes 二进制数据
     * @param filePath 文件生成目录
     */
    public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
        InputStream in = new ByteArrayInputStream(bytes);   
        File destFile = new File(filePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        destFile.createNewFile();
        OutputStream out = new FileOutputStream(destFile);
        byte[] cache = new byte[CACHE_SIZE];
        int nRead = 0;
        while ((nRead = in.read(cache)) != -1) {   
            out.write(cache, 0, nRead);
            out.flush();
        }
        out.close();
        in.close();
    }
    
    
}

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是一种非对称加密算法,其公钥私钥是成对生成的。以下是RSA生成公钥私钥以及加解密的步骤: 1. 生成RSA公钥私钥: 首先需要随机生成两个大素数p和q,计算n = p * q,再选取一个整数e(一般为65537),计算d = e^-1 mod ((p-1) * (q-1))。 生成公钥为(n, e),私钥为(n, d)。 2. RSA加密: 假设要将明文M加密为密文C,使用公钥(n, e)进行加密,计算C = M^e mod n。 3. RSA解密: 使用私钥(n, d)进行解密,计算M = C^d mod n。 以下是一个简单的RSA加解密的C语言实现示例: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/bio.h> #include <openssl/rsa.h> #include <openssl/pem.h> int main() { // 生成RSA公钥私钥 RSA *rsa = RSA_generate_key(2048, 65537, NULL, NULL); if (rsa == NULL) { printf("Failed to generate RSA key pair.\n"); return -1; } // 获取公钥私钥 BIO *pubBio = BIO_new(BIO_s_mem()); BIO *priBio = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPublicKey(pubBio, rsa); PEM_write_bio_RSAPrivateKey(priBio, rsa, NULL, NULL, 0, NULL, NULL); // 获取公钥私钥字符串 char pubKey[1024] = {0}; char priKey[4096] = {0}; BIO_read(pubBio, pubKey, sizeof(pubKey)); BIO_read(priBio, priKey, sizeof(priKey)); // 输出公钥私钥 printf("Public Key:\n%s\n", pubKey); printf("Private Key:\n%s\n", priKey); // 加密明文 char *plaintext = "Hello World!"; int plaintextLen = strlen(plaintext) + 1; char ciphertext[4096] = {0}; int ciphertextLen = RSA_public_encrypt(plaintextLen, (unsigned char *)plaintext, (unsigned char *)ciphertext, rsa, RSA_PKCS1_PADDING); if (ciphertextLen == -1) { printf("Failed to encrypt plaintext.\n"); return -1; } // 输出密文 printf("Ciphertext:\n"); for (int i = 0; i < ciphertextLen; i++) { printf("%02x", ciphertext[i]); } printf("\n"); // 解密密文 char decrypted[4096] = {0}; int decryptedLen = RSA_private_decrypt(ciphertextLen, (unsigned char *)ciphertext, (unsigned char *)decrypted, rsa, RSA_PKCS1_PADDING); if (decryptedLen == -1) { printf("Failed to decrypt ciphertext.\n"); return -1; } // 输出解密后的明文 printf("Decrypted plaintext: %s\n", decrypted); // 释放资源 RSA_free(rsa); BIO_free_all(pubBio); BIO_free_all(priBio); return 0; } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Male晓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值