RSA公钥加密私钥解密实例

public class RSACrypt {

    /**
     * 生成RAS公钥与私钥字符串,直接返回
     *
     * @return
     */
    public static HashMap<String, String> getKeys() {
        HashMap<String, String> map = new HashMap<String, String>();
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 初始化密钥对生成器,密钥大小为96-1024位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到公钥字符串
        String publicKey = base64ToStr(keyPair.getPublic().getEncoded());
        // 得到私钥字符串
        String privateKey = base64ToStr(keyPair.getPrivate().getEncoded());
        map.put("publicKey", publicKey);
        map.put("privateKey", privateKey);
        return map;
    }

    /**
     * 根据公钥字符串加载公钥
     *
     * @param publicKeyStr 公钥字符串
     * @return
     * @throws Exception
     */
    public static RSAPublicKey loadPublicKey(String publicKeyStr) throws Exception {
        try {
            byte[] buffer = javax.xml.bind.DatatypeConverter.parseBase64Binary(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法", e);
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法", e);
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空", e);
        }
    }

    /**
     * 根据私钥字符串加载私钥
     *
     * @param privateKeyStr 私钥字符串
     * @return
     * @throws Exception
     */
    public static RSAPrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
        try {
            byte[] buffer = javax.xml.bind.DatatypeConverter.parseBase64Binary(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法", e);
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法", e);
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空", e);
        }
    }

    /**
     * 公钥加密
     *
     * @param publicKey     公钥
     * @param plainTextData 明文数据
     * @return
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(plainTextData);
            return base64ToStr(output);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }
    public static String encrypt(byte[] plainTextData) throws Exception {
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, RSACrypt.loadPublicKey(pk));
            byte[] output = cipher.doFinal(plainTextData);
            return base64ToStr(output);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }
    
    /**
     * 私钥解密
     *
     * @param privateKey 私钥
     * @param cipherData 密文数据
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
        if (privateKey == null) {
            throw new Exception("解密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(cipherData);
            return new String(output);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            e.printStackTrace();
            throw new Exception("密文数据已损坏");
        }
    }
    public static String decrypt(byte[] cipherData) throws Exception {
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, RSACrypt.loadPrivateKey(sk));
            byte[] output = cipher.doFinal(cipherData);
            return new String(output);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            e.printStackTrace();
            throw new Exception("密文数据已损坏");
        }
    }
    public static String base64ToStr(byte[] b) {
        return javax.xml.bind.DatatypeConverter.printBase64Binary(b);
    }

    public static byte[] strToBase64(String str) {
        return javax.xml.bind.DatatypeConverter.parseBase64Binary(str);
    }
    
}

  生成秘钥对,加密数据、解密数据

public static void main(String[] args) throws Exception {
    //初始化阶段,初始化后生成秘钥对
    //公钥发送给消息发送方用于加密传输数据;私钥严格保存于消息接收方,收到加密的消息之后进行解密
    HashMap<String, String> map = RSACrypt.getKeys();
    String privateKeyStr=map.get("privateKey");
    String publicKeyStr=map.get("publicKey");
    System.out.println("初始化私钥为:"+privateKeyStr);
    System.out.println("初始化共钥为:"+publicKeyStr);

    //消息发送方
    String originData="你是收破烂的么?";
    System.out.println("信息原文:"+originData);
    String encryptData=RSACrypt.encrypt(RSACrypt.loadPublicKey(publicKeyStr),originData.getBytes());
    System.out.println("加密后:"+encryptData);

    //消息接收方
    String decryptData=RSACrypt.decrypt(RSACrypt.loadPrivateKey(privateKeyStr),RSACrypt.strToBase64(encryptData));
    System.out.println("解密后:"+decryptData);
}

  结果输出

初始化私钥为:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAI2SyRvMxZTrlRx6oHav8lCECHX5wZ/pPkAsl1RIh/NMfV5wjN+3kGZrG6NEvI+xCuwwFGn8GwUDgqC6Hw5nA15chuRprZFDaXa9hFrC6r6jtQ6MPOsqdaDJSfpJIY64fZqoVLKdibV783mfL175n9IkaDuw3msumJyDOsgplIJ/AgMBAAECgYApC8rFBZyvbZIg3KjTYHXXxEATvGLX8y76OjNx20mXT7D1hZpCbp0uJJWxw4cL/h+VlOcGR3KqBHeGFBBXA6Tk8miMo/ZqXHVWF0pFc2eVbhpn3llOy+HHA92KRFakY14UWK5xGk+rU7y7/FJ2ehWbPr+HQES+1Z8B2RmLwUqU4QJBANqr3GZGtAnrkmK0Y4eNBa7oVyWM8lDqa40h6rCMifzPxNGw1DH5Yr55WN89z0MRJcJXHfoLgJzecbq4g8OMVpECQQClvaxLvMpZw3xqb6akE92pLZZlSKjKckHkE3/XTM6ZPF6o44SgSV2surUnYhA86KDDvEpMiR+YDFUdJ3z8vHAPAkEA2EMmG2SLhFAdm07KLHIVD9Gq9nE56TqeGZtUjzy+72/QOI4InlAFD1nVwhtQEwUvcc9Uz0l27i21DrSTY980cQJBAJUMuvqtgCgzdhrd57Wcq/WtqpfRPQI6uGjc5FYBm7YQpWwql6Xx9I0Wpz0Qolu0NIdyODsWAdSiGpUKYwuChx8CQETYzUXnFSrK4dp5na87j4nDZs/qeevfjBuhKiGIsSQ3SOTKdmpnVZRkGs6H/eEVcmYr1/H9T20Wx1A3oTmPMuE=
初始化共钥为:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCNkskbzMWU65UceqB2r/JQhAh1+cGf6T5ALJdUSIfzTH1ecIzft5BmaxujRLyPsQrsMBRp/BsFA4Kguh8OZwNeXIbkaa2RQ2l2vYRawuq+o7UOjDzrKnWgyUn6SSGOuH2aqFSynYm1e/N5ny9e+Z/SJGg7sN5rLpicgzrIKZSCfwIDAQAB
信息原文:你是收破烂的么?
加密后:XeIAoNZlyn+Mk17wsdPpl8SDlaq0B8NbIvQFVg9Ja+YHxuKretNMu61IRY5EFyPL/dXC/6KiDDINglP2HRX4JNbRZgzZd1rkqExW219psHQOhFzbFYZ3yKuI72C7S4/sqIM1eqlnkvIGBhJNLwOfzF6VjplsbHAiQ4fDhA57XI8=
解密后:你是收破烂的么?

  

posted on 2020-12-03 17:27  cwone  阅读(1238)  评论(0编辑  收藏  举报