JAVA加密&解密——非对称加密算法RSA

本文介绍RSA算法的基本原理及其在Java中的实现方法,包括密钥生成、数字签名、加解密等功能,并通过测试代码验证其正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RSA简介

RSA算法出现于1978年,它是第一个既能用于数据加密也能用于数字签名的算法,算法的名字以发明者的名字命名:Ron Rivest, AdiShamir 和Leonard Adleman,RSA同时有两把钥匙:公钥与私钥

JAVA实现代码

package com.share.security;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.log4j.Logger;

import com.share.util.Base64;

/**
 * RSA签名公共类
 * @description 
 * @version 1.0
 * @author zhufj
 * @date 2015-9-14 下午12:08:24
 */
public class RSAUtil{

    private static Logger  log = Logger.getLogger(RSAUtil.class);
    private static RSAUtil instance;
    private static String PUBLIC_KEY_FILE_NAME="_RSAKey_public.txt";
    private static String PRIVATE_KEY_FILE_NAME="_RSAKey_public.txt";
    private static final String KEY_ALGORITHM = "RSA";//RSA算法:加解密  
    private static final String SIGNATURE_ALGORITHM = "MD5withRSA";//RSA算法:数字签名  

    private RSAUtil()
    {
    }

    public static RSAUtil getInstance()
    {
        if (null == instance)
            return new RSAUtil();
        return instance;
    }
     /***************************************************************************************
     *********                       RSA秘钥生成                                                                                                              **********
     ***************************************************************************************/
    /**
     * 公钥、私钥文件生成
     * @param keyPath:保存文件的路径
     * @param keyFlag:文件名前缀
     */
    public void generateKeyPair(String key_path, String name_prefix)
    {
        java.security.KeyPairGenerator keygen = null;
        try
        {
            keygen = java.security.KeyPairGenerator.getInstance(KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException e1)
        {
            log.error(e1.getMessage());
        }
        SecureRandom secrand = new SecureRandom();
        secrand.setSeed("21cn".getBytes()); // 初始化随机产生器
        keygen.initialize(1024, secrand);
        KeyPair keys = keygen.genKeyPair();
        PublicKey pubkey = keys.getPublic();
        PrivateKey prikey = keys.getPrivate();

        String pubKeyStr = Base64.getBASE64(pubkey.getEncoded());
        String priKeyStr = Base64.getBASE64(prikey.getEncoded());
        File file = new File(key_path);
        if (!file.exists())
        {
            file.mkdirs();
        }
        try
        {
            // 保存私钥
            FileOutputStream fos = new FileOutputStream(new File(key_path
                    + name_prefix + PRIVATE_KEY_FILE_NAME));
            fos.write(priKeyStr.getBytes());
            fos.close();
            // 保存公钥
            fos = new FileOutputStream(new File(key_path + name_prefix
                    + PUBLIC_KEY_FILE_NAME));
            fos.write(pubKeyStr.getBytes());
            fos.close();
        } catch (IOException e)
        {
            log.error(e.getMessage());
        }
    }

    /**
     * 读取密钥文件内容
     * @param key_file:文件路径
     * @return
     */
    public static String getKeyContent(String key_file)
    {
        File file = new File(key_file);
        BufferedReader br = null;
        InputStream ins = null;
        StringBuffer sReturnBuf = new StringBuffer();
        try
        {
            ins = new FileInputStream(file);
            br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
            String readStr = null;
            readStr = br.readLine();
            while (readStr != null)
            {
                sReturnBuf.append(readStr);
                readStr = br.readLine();
            }
        } catch (IOException e)
        {
            return null;
        } finally
        {
            if (br != null)
            {
                try
                {
                    br.close();
                    br = null;
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (ins != null)
            {
                try
                {
                    ins.close();
                    ins = null;
                } catch (IOException e)
                {
                    e.printStackTrace();
                }

            }
        }
        return sReturnBuf.toString();
    }  
                                                                                                                        /***************************************************************************************
*********                       RSA数字签名                                                                                                              **********
  ***************************************************************************************/
    /**
     * 签名处理
     * @param prikeyvalue:私钥文件
     * @param sign_str:签名源内容
     * @return
     */
    public static String sign(String prikeyvalue, String sign_str)
    {
        try
        {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64
                    .getBytesBASE64(prikeyvalue));
            KeyFactory keyf = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey myprikey = keyf.generatePrivate(priPKCS8);
            // 用私钥对信息生成数字签名
            java.security.Signature signet = java.security.Signature
                    .getInstance(SIGNATURE_ALGORITHM);
            signet.initSign(myprikey);
            signet.update(sign_str.getBytes("UTF-8"));
            byte[] signed = signet.sign(); // 对信息的数字签名
            return new String(org.apache.commons.codec.binary.Base64.encodeBase64(signed));
        } catch (java.lang.Exception e)
        {
            log.error("签名失败," + e.getMessage());
        }
        return null;
    }

    /**
     * 数字签名验证
     * @param pubkeyvalue:公钥
     * @param oid_str:源串
     * @param signed_str:签名结果串
     * @return
     */
    public static boolean checksign(String pubkeyvalue, String oid_str,
            String signed_str)
    {
        try
        {
            X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(Base64
                    .getBytesBASE64(pubkeyvalue));
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey pubKey = keyFactory.generatePublic(bobPubKeySpec);
            byte[] signed = Base64.getBytesBASE64(signed_str);// 这是SignatureData输出的数字签名
            java.security.Signature signetcheck = java.security.Signature
                    .getInstance(SIGNATURE_ALGORITHM);
            signetcheck.initVerify(pubKey);
            signetcheck.update(oid_str.getBytes("UTF-8"));
            return signetcheck.verify(signed);
        } catch (java.lang.Exception e)
        {
            log.error("签名验证异常," + e.getMessage());
        }
        return false;
    }                          


    /***************************************************************************************
     *********                       RSA加解密                                                                                                                  **********
     ***************************************************************************************/
    /**
     * 用私钥加密
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = Base64.getBytesBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        return cipher.doFinal(data);
    }

    /**
     * 用公钥解密
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] data, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = Base64.getBytesBASE64(key);

        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);

        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        return cipher.doFinal(data);
    }

    /**
     * 用公钥加密
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, String key)
            throws Exception {
        // 对公钥解密
        byte[] keyBytes = Base64.getBytesBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        return cipher.doFinal(data);
    }

    /**
     * 用私钥解密
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] data, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = Base64.getBytesBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

}

JAVA测试代码

package com.share.security;

import static org.junit.Assert.*;

import org.junit.Test;

public class RSATest {
    private static String KEY_PATH="D:\\CertFiles\\inpour\\";//保存RSA秘钥文件路径
    private static String PUBLIC_KEY_FILE_NAME="_RSAKey_public.txt";
    private static String PRIVATE_KEY_FILE_NAME="_RSAKey_public.txt";
    private static final String KEY_ALGORITHM = "RSA";//RSA算法:加解密  
    private static final String SIGNATURE_ALGORITHM = "MD5withRSA";//RSA算法:数字签名  
    /**
     * 生成密钥串测试
     */
    @Test
    public void generateKeyPairTest() {
        RSAUtil.getInstance().generateKeyPair(KEY_PATH,"test");
    }
    /**
     * 数字签名测试
     */
    @Test
    public void signTest() {
        //从文件获取(RSA)公钥、私钥
        @SuppressWarnings("static-access")
        String RSA_PUBLIC=RSAUtil.getInstance().getKeyContent(KEY_PATH+"test_RSAKey_public.txt");
        @SuppressWarnings("static-access")
        String RSA_PRIVATE=RSAUtil.getInstance().getKeyContent(KEY_PATH+"test_RSAKey_private.txt");
        String signData="test";
        String sign = RSAUtil.sign(RSA_PRIVATE, signData);
        System.out.println("签名源串:"+signData);
        System.out.println("签名串:"+sign);
        assertTrue(RSAUtil.checksign(RSA_PUBLIC, signData, sign));
    }
    /**
     * 私钥加密公钥解密测试
     * @throws Exception 
     */
    @Test
    public void privateEncryptAndPublicDecrypt() throws Exception {
        System.out.println("私钥加密——公钥解密");
        // 从文件获取(RSA)公钥、私钥
        @SuppressWarnings("static-access")
        String RSA_PUBLIC = RSAUtil.getInstance().getKeyContent(
                KEY_PATH + "test_RSAKey_public.txt");
        @SuppressWarnings("static-access")
        String RSA_PRIVATE = RSAUtil.getInstance().getKeyContent(
                KEY_PATH + "test_RSAKey_private.txt");
        String inputStr = "test";
        byte[] data = inputStr.getBytes();
        byte[] encodedData = RSAUtil.encryptByPrivateKey(data, RSA_PRIVATE);
        byte[] decodedData = RSAUtil.decryptByPublicKey(encodedData, RSA_PUBLIC);
        String outputStr = new String(decodedData);
        System.out.println("加密前: " + inputStr + "\n" + "解密后: " + outputStr);
        assertEquals(inputStr, outputStr);

    }
    /**
     * 公钥加密私钥解密测试
     * @throws Exception 
     */
    @Test
    public void publicEncryptAndPrivateDecrypt() throws Exception {
        System.out.println("公钥加密——私钥解密");
        // 从文件获取(RSA)公钥、私钥
        @SuppressWarnings("static-access")
        String RSA_PUBLIC = RSAUtil.getInstance().getKeyContent(
                KEY_PATH + "test_RSAKey_public.txt");
        @SuppressWarnings("static-access")
        String RSA_PRIVATE = RSAUtil.getInstance().getKeyContent(
                KEY_PATH + "test_RSAKey_private.txt");
        String inputStr = "abc";
        byte[] data = inputStr.getBytes();
        byte[] encodedData = RSAUtil.encryptByPublicKey(data, RSA_PUBLIC);
        byte[] decodedData = RSAUtil.decryptByPrivateKey(encodedData,
                RSA_PRIVATE);
        String outputStr = new String(decodedData);
        System.out.println("加密前: " + inputStr + "\n" + "解密后: " + outputStr);
        assertEquals(inputStr, outputStr);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值