Java生成公钥密钥 密钥 签名

该代码展示了如何使用RSA算法进行加密、解密、签名和验签操作。首先通过`EncryptionAndDecryption`类初始化公钥和私钥,然后进行加密和解密演示,同时实现了签名和验证签名的功能,确保数据的完整性和安全性。
摘要由CSDN通过智能技术生成
package com.zjjhy.controller.api;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.*;
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;

public class EncryptionAndDecryption {
        public static final String KEY_ALGORITHM = "RSA";
        private static final String PUBLIC_KEY = "RSAPublicKey";
        private static final String PRIVATE_KEY = "RSAPrivateKey";
        public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
        /**
         * RSA最大加密明文大小
         */
        private static final int MAX_ENCRYPT_BLOCK = 117;

        /**
         * RSA最大解密密文大小
         */
        private static final int MAX_DECRYPT_BLOCK = 128;

        //获得公钥字符串
        public  String getPublicKeyStr(Map<String, Object> keyMap) throws Exception {
            //获得map中的公钥对象 转为key对象
            Key key = (Key) keyMap.get(PUBLIC_KEY);
            //编码返回字符串
            return encryptBASE64(key.getEncoded());
        }


        //获得私钥字符串
        public String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception {
            //获得map中的私钥对象 转为key对象
            Key key = (Key) keyMap.get(PRIVATE_KEY);
            //编码返回字符串
            return encryptBASE64(key.getEncoded());
        }

        //获取公钥
        public PublicKey getPublicKey(String key) throws Exception {
            byte[] keyBytes;
            keyBytes = (new BASE64Decoder()).decodeBuffer(key);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicKey = keyFactory.generatePublic(keySpec);
            return publicKey;
        }

        //获取私钥
        public PrivateKey getPrivateKey(String key) throws Exception {
            byte[] keyBytes;
            keyBytes = (new BASE64Decoder()).decodeBuffer(key);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            return privateKey;
        }

        //解码返回byte
        public  byte[] decryptBASE64(String key) throws Exception {
            return (new BASE64Decoder()).decodeBuffer(key);
        }


        //编码返回字符串
        public  String encryptBASE64(byte[] key) throws Exception {
            return (new BASE64Encoder()).encodeBuffer(key);
        }

        public  Map<String, Object> initKey() throws Exception {
            //获得对象 KeyPairGenerator 参数 RSA 1024个字节
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            keyPairGen.initialize(1024);
            //通过对象 KeyPairGenerator 获取对象KeyPair
            KeyPair keyPair = keyPairGen.generateKeyPair();
            //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            //公私钥对象存入map中`
            Map<String, Object> keyMap = new HashMap<String, Object>(2);
            keyMap.put(PUBLIC_KEY, publicKey);
            keyMap.put(PRIVATE_KEY, privateKey);
            return keyMap;
        }

        //***************************签名和验证*******************************
        public  byte[] sign(byte[] data, String privateKeyStr) throws Exception {
            PrivateKey priK = getPrivateKey(privateKeyStr);
            Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
            sig.initSign(priK);
            sig.update(data);
            return sig.sign();
        }
        //***************************验证*******************************
        public  boolean verify(byte[] data, byte[] sign, String publicKeyStr) throws Exception {
            PublicKey pubK = getPublicKey(publicKeyStr);
            Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
            sig.initVerify(pubK);
            sig.update(data);
            return sig.verify(sign);
        }

        //************************加密**************************
        public  byte[] encrypt(byte[] plainText, String publicKeyStr) throws Exception {
            PublicKey publicKey = getPublicKey(publicKeyStr);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            int inputLen = plainText.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            int i = 0;
            byte[] cache;
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(plainText, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(plainText, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptText = out.toByteArray();
            out.close();
            return encryptText;
        }
        //************************解密**************************
        public  byte[] decrypt(byte[] encryptText, String privateKeyStr) throws Exception {
            PrivateKey privateKey = getPrivateKey(privateKeyStr);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            int inputLen = encryptText.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptText, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptText, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] plainText = out.toByteArray();
            out.close();
            return plainText;
        }

}

package com.zjjhy.controller.api;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("api/tools")
public class ToolsController extends AbstractApiController {

    @Autowired
    ToolsService toolsService;

    Key key=new Key();

    EncryptionAndDecryption mncr=new EncryptionAndDecryption();

    //发生密文
    @ResponseBody
    @RequestMapping(value = "/ciphertext", method = RequestMethod.GET, headers = "Accept=application/json")
    public ApiResponseObject ciphertext(@Param("input") String input)  {
        Map<String, Object> keyMap;
        byte[] cipherText;
        try {
            keyMap=mncr.initKey();
            //公钥
            String publicKey = mncr.getPublicKeyStr(keyMap);
            //密钥
            String privateKey = mncr.getPrivateKeyStr(keyMap);
            //密文
            cipherText=mncr.encrypt(input.getBytes(),publicKey);

            String keySthring=mncr.encryptBASE64(cipherText);
            key.setCiphertext(keySthring);
            key.setPrivateKey(privateKey);
        }catch (Exception e){
            e.printStackTrace();
            return reponseJSON(ApiResponseEnum.FAIL.getCode(),ApiResponseEnum.FAIL.getName(),new AjaxResult(false,"失败"));
        }
        return reponseJSON(ApiResponseEnum.SUCCESS.getCode(),ApiResponseEnum.SUCCESS.getName(),key);

    }
    //密文解密
    @ResponseBody
    @RequestMapping(value = "/ciphertextDecryption", method = RequestMethod.POST, headers = "Accept=application/json")
    public ApiResponseObject ciphertextDecryption(@RequestBody Key key){
        byte[] plainText = new byte[0];
       try {
           System.out.println(key);
           byte[] keyByte=mncr.decryptBASE64(key.getCiphertext());
           //开始解密
            plainText = mncr.decrypt(keyByte, key.getPrivateKey());
       }catch (Exception e){
           e.printStackTrace();
       }
        return reponseJSON(ApiResponseEnum.SUCCESS.getCode(),ApiResponseEnum.SUCCESS.getName(),new String(plainText));
    }
    //发送签名
    @ResponseBody
    @RequestMapping(value = "/sendSignature", method = RequestMethod.GET, headers = "Accept=application/json")
    public ApiResponseObject sendSignature(@Param("signature") String signatures)  {
        Map<String, Object> keyMap;
        byte[] signature;
        try {
            keyMap=mncr.initKey();
            //公钥
            String publicKey = mncr.getPublicKeyStr(keyMap);
            //密钥
            String privateKey = mncr.getPrivateKeyStr(keyMap);
            System.out.println("\n原文:" + signatures);
            signature= mncr.sign(signatures.getBytes(), privateKey);

            String signatureContent=mncr.encryptBASE64(signature);

            key.setSignature(signatures);
            key.setSignatureContent(signatureContent);
            key.setPublicKey(publicKey);

            System.out.println("被签名的内容--------"+new String(signature));
            boolean status = mncr.verify(signatures.getBytes(), signature, publicKey);
        }catch (Exception e){
            e.printStackTrace();
            return reponseJSON(ApiResponseEnum.FAIL.getCode(),ApiResponseEnum.FAIL.getName(),new AjaxResult(false,"失败"));
        }
        return reponseJSON(ApiResponseEnum.SUCCESS.getCode(),ApiResponseEnum.SUCCESS.getName(),key);
    }
    //签名验证
    @ResponseBody
    @RequestMapping(value = "/signatureVerification", method = RequestMethod.GET, headers = "Accept=application/json")
    public ApiResponseObject signatureVerification(@RequestBody Key key){

        try {
            byte[] signatureContent=mncr.decryptBASE64(key.getSignatureContent());

            boolean status = mncr.verify(key.getSignature().getBytes(), signatureContent, key.getPublicKey());
            if (status){
                return reponseJSON(ApiResponseEnum.SUCCESS.getCode(),ApiResponseEnum.SUCCESS.getName(),new AjaxResult(false,"成功"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return reponseJSON(ApiResponseEnum.FAIL.getCode(),ApiResponseEnum.FAIL.getName(),new AjaxResult(false,"失败"));
    }
    //公钥密钥
    @ResponseBody
    @RequestMapping(value = "/publicKey", method = RequestMethod.GET, headers = "Accept=application/json")
    public ApiResponseObject publicKey()  {
        Map<String, Object> keyMap;
        Map<String,String> map = new HashMap<>();
        try {
            keyMap=mncr.initKey();
            //公钥
            String publicKey = mncr.getPublicKeyStr(keyMap);
            //密钥
            String privateKey = mncr.getPrivateKeyStr(keyMap);
            map.put("publicKey",publicKey);
            map.put("privateKey",privateKey);
        }catch (Exception e){
            e.printStackTrace();
            return reponseJSON(ApiResponseEnum.FAIL.getCode(),ApiResponseEnum.FAIL.getName(),new AjaxResult(false,"失败"));
        }
        return reponseJSON(ApiResponseEnum.SUCCESS.getCode(),ApiResponseEnum.SUCCESS.getName(),map);

    }
}

package com.zjjhy.model;

public class Key {
  private   String publicKey;//公钥
  private  String privateKey;//密钥
  private String ciphertext;//密文
  private String plaintext;//明文
  private String signature;//签名
  private  String signatureContent;//签名内容


    public String getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(String publicKey) {
        this.publicKey = publicKey;
    }

    public String getPrivateKey() {
        return privateKey;
    }

    public void setPrivateKey(String privateKey) {
        this.privateKey = privateKey;
    }

    public String getCiphertext() {
        return ciphertext;
    }

    public void setCiphertext(String ciphertext) {
        this.ciphertext = ciphertext;
    }

    public String getPlaintext() {
        return plaintext;
    }

    public void setPlaintext(String plaintext) {
        this.plaintext = plaintext;
    }

    public String getSignature() {
        return signature;
    }

    public void setSignature(String signature) {
        this.signature = signature;
    }

    public String getSignatureContent() {
        return signatureContent;
    }

    public void setSignatureContent(String signatureContent) {
        this.signatureContent = signatureContent;
    }

    @Override
    public String toString() {
        return "Key{" +
                "publicKey='" + publicKey + '\'' +
                ", privateKey='" + privateKey + '\'' +
                ", ciphertext='" + ciphertext + '\'' +
                ", plaintext='" + plaintext + '\'' +
                ", signature='" + signature + '\'' +
                ", signatureContent='" + signatureContent + '\'' +
                '}';
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

实习证明徐学长

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

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

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

打赏作者

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

抵扣说明:

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

余额充值