当前位置:   article > 正文

公钥和私钥_私钥和公钥

私钥和公钥

简介

公钥和私钥就是俗称的不对称加密方式,是从以前的对称加密(使用用户名与密码)方式的提高。用电子邮件的方式说明一下原理。
使用公钥与私钥的目的就是实现安全的电子邮件,必须实现如下目的:

  1. 我发送给你的内容必须加密,在邮件的传输过程中不能被别人看到
  2. 必须保证是我发送的邮件,不是别人冒充我的

要达到这样的目标必须发送邮件的两人都有公钥和私钥。
公钥,就是给大家用的,你可以通过电子邮件发布,可以通过网站让别人下载,公钥其实是用来加密/验章用的。
私钥,就是自己的,必须非常小心保存,最好加上密码,私钥是用来解密/签章,首先就Key的所有权来说,私钥只有个人拥有。
公钥与私钥的作用是:用公钥加密的内容只能用私钥解密,用私钥加密的内容只能用公钥解密。

比如说,我要给你发送一个加密的邮件。首先,我必须拥有你的公钥,你也必须拥有我的公钥。

  • 首先,我用你的公钥给这个邮件加密,这样就保证这个邮件不被别人看到,而且保证这个邮件在传送过程中没有被修改。你收到邮件后,用你的私钥就可以解密,就能看到内容。
  • 其次,我用我的私钥给这个邮件加密,发送到你手里后,你可以用我的公钥加密。因为私钥只有我手里有,这样就保证了这个邮件是我发送的。
  • 当A->B资料时,A会使用B的公钥加密,这样才能确保只有B能解开,否则普通大众都能解开加密的讯息,就是去了资料的保密性。验证方面则是使用签验章的机制,A传资料给大家时,会以自己的私钥做签章,如此所有收到讯息的人都可以用A的公钥进行验章,便可确认讯息是由A发出来的了。

加密算法包括对称加密和非对称加密,对称加密就是加密和解密用一个密钥,就像电报加密一样,需要一个密码本,发送方通过它加密,接收方通过它解密,因此密码本非常重要,一旦泄露就会所有信息被窃取。而非对称加密有两个密钥,公钥和私钥。接收方先生成一对公钥私钥,公钥可以直接不加密发送给发送方,任何人都可以拿到。然后发送方用公钥加密,发送给接收方后,接收方用私钥可以解密,并且只有私钥能解密,公钥不能解密,只能加密。
著名的RSA算法就是非对称加密的一种,是基于大数难以进行质因数分解设计的。加密等级越高,RSA位数就越长,目前常用1024bits。并且RSA算法除了加密以外还可以实现数字签名。就是证明A发送的信息确实是A发出的。公钥和私钥实际上地位平等,可以互相加密解密。即用公钥加密的密文可以用私钥解密,这就是加密过程;反过来,用私钥加密的密文可以用公钥解密,也就是说大众可以用公钥对A发出的密文解密来验证信息确实是A发出的,这就是数字签名。
RSA速度很慢,一般只对少量信息进行加密。常用的做法是用RSA给对称加密密钥加密,发送给接收方。然后接收方解密知道了对称加密密钥,双方再通过对称加密方式通讯。

用java实现的代码如下:

在这里插入图片描述

RsaEncrypt .java

注: 加密算法的各种形式参考
https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html

package com.sm.test1;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;

/**
 * 对文件加签、验签工具类
 * 对文件加签、验签工具类
 * 生成私钥:openssl genrsa -out rsa_private_key.pem 1024
 * 私钥还不能直接被使用,需要进行PKCS#8编码:openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt
 * 根据私钥生成公钥:openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
 * 使用私钥sha512签名:openssl dgst -sha512 -sign rsa_private_key.pem -out xx.tar.gz.sign xx.tar.gz
 * 使用公钥sha512验签:openssl dgst -verify rsa_public_key.pem -sha512 -signature xx.tar.gz.sign xx.tar.gz
 *
 * @author miracle_8
 * @date 2019/12/3
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
public class RsaEncrypt {

    /**
     *
     * RSA签名
     *
     * @param data 待签名的字符串
     * @param privateKey rsa私钥字符串
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public byte[] rsaSign(byte[] data, RSAPrivateKey privateKey)
            throws SignatureException {
        try {
            Signature signature = Signature.getInstance("SHA512withRSA");
            signature.initSign(privateKey);
            signature.update(data);

            byte[] signed = signature.sign();
            return signed;
        } catch (Exception e) {
            throw new SignatureException("RSAcontent = " + data + "; charset = ", e );
        }
    }

    /**
     * RSA验签
     *
     * @param data 被签名的内容
     * @param sign 签名后的结果
     * @param publicKey rsa公钥
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public boolean verify(byte[] data, byte[] sign, RSAPublicKey publicKey)
        throws SignatureException {
        try {
            Signature signature = Signature.getInstance("SHA512withRSA");
            signature.initVerify(publicKey);
            signature.update(data);
            return signature.verify(sign);
        } catch (Exception e) {
            throw new SignatureException("RSA验证签名[content = " + data + "; charset = ; signature = " + sign + "]发生异常!", e);
        }
    }

    /**
     * 私钥  通过Base64Utils.encode(rsaEncrypt.getPrivateKey().getEncoded()) 可以获取
     */
    private RSAPrivateKey privateKey;

    /**
     * 公钥   通过Base64Utils.encode(rsaEncrypt.getPublicKey().getEncoded()) 可以获取
     */
    private RSAPublicKey publicKey;

    /**
     * 字节数据转字符串专用集合
     */
    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 获取私钥
     *
     * @param
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public RSAPrivateKey getPrivateKey() {
        return privateKey;
    }

    /**
     * 获取公钥
     *
     * @param
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public RSAPublicKey getPublicKey() {
        return publicKey;
    }

    /**
     * 随机生成密钥对
     *
     * @param
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public void genKeyPair() {
        KeyPairGenerator keyPairGenerator = null;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        keyPairGenerator.initialize(1024, new SecureRandom());
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        this.privateKey = (RSAPrivateKey) keyPair.getPrivate();
        this.publicKey = (RSAPublicKey) keyPair.getPublic();
    }

    /**
     * 从.pem文件中取得私钥
     *
     * @param
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public String getPrivateKeyFromFile(String filePath) {
        String strPrivateKey = "";
        try {
            BufferedReader privateKey = new BufferedReader(new FileReader(filePath));
            String line = "";
            while ((line = privateKey.readLine()) != null) {
                strPrivateKey += line;
            }
            privateKey.close();
            strPrivateKey = strPrivateKey.replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strPrivateKey;
    }

    /**
     * 从.pem文件中取得公钥
     *
     * @param
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public String getPublicKeyFromFile(String filePath) {
        String strPublicKey = "";
        try {
            BufferedReader publicKey = new BufferedReader(new FileReader(filePath));
            String line = "";
            while ((line = publicKey.readLine()) != null) {
                strPublicKey += line;
            }
            publicKey.close();
            strPublicKey = strPublicKey.replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strPublicKey;
    }

    /**
     * 从字符串中加载公钥
     *
     * @param publicKeyStr 公钥字符串
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public void loadPublicKey(String publicKeyStr)
        throws Exception{
        try {
            byte[] buffer = Base64Utils.decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer); //  通过x509编码后的
            this.publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
        }  catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        }catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    /**
     * 加载私钥
     *
     * @param privateKeyStr 私钥字符串 必须是已经经过PKCS8编码后的字符串, 原字符串不可以
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public void loadPrivateKey(String privateKeyStr)
        throws Exception {
        try {
            byte[] buffer = Base64Utils.decode(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer); // PKCS8编码后的
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            this.privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }

    /**
     * 加密过程
     *
     * @param publicKey 公钥
     * @param plainTextData 明文数据
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
        throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(plainTextData);
            return 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
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
            throws Exception{
        if (privateKey == null) {
            throw new Exception("解密私钥为空, 请设置");
        }

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(cipherData);
            return 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 data 输入数据
     * @return byte[]
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static String byteArrayToString(byte[] data) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
            // 取出字节的低四位 作为索引得到相应的十六进制标识符
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0)]);
            if (i < data.length - 1) {
                stringBuilder.append(' ');
            }
        }
        return stringBuilder.toString();
    }

    /**
     * byte转换hex函数
     *
     * @param
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static String byteToHex(byte[] byteArray) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                stringBuilder.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            } else {
                stringBuilder.append(Integer.toHexString(0xFF & byteArray[i]));
            }
        }
        return stringBuilder.toString();
    }

    public static byte[] readFileByBytes(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        byte[] txt = new byte[(int) file.length()];
        try {
            in = new FileInputStream(file);
            int tempByte;
            int i = 0;
            while ((tempByte = in.read()) != -1) {
                txt[i] = (byte) tempByte;
                i++;
            }
            in.close();
            return txt;
        } catch (IOException e) {
            e.printStackTrace();
            return txt;
        }
    }

    public static void main(String[] args) {
        RsaEncrypt rsaEncrypt = new RsaEncrypt();
        try {
//            String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPTrsUJ26WDSEQwKuAJhQ6XTNHKl1/+bWeyKRQKb0jeCyuiChMxN/qYSgg2BvS2bP51Rb5P9/UE1Rxm5drr3RYNMDvQoXBuA+rHiUX3wkdXmWSaktVbfe5C95N5FCF2jyLMIuWmrMk6Wo3r5MXrCb54A6zU7SzO/r7F0VkpBh9KwIDAQAB";
            String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwjCrXvf3JWq1cGwr7CyXzfUHolqKUdwyIb8MQUMCJFOPTzKB1wyFAacOogvSB3XkAUT/M9QTDsImYLRk7ISijQXekXcIEKwqej8TVsOaNIp0TITAmAQcusXpPuIpVa19q3PTpAzgEtGdW7ZKiqieom8Q3U00rXU+CdqKgJaE75QIDAQAB";
            rsaEncrypt.loadPublicKey(publicKey);
            System.out.println("加载公钥成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("加载公钥失败");
        }

        try {
//            String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAM9OuxQnbpYNIRDAq4AmFDpdM0cqXX/5tZ7IpFApvSN4LK6IKEzE3+phKCDYG9LZs/nVFvk/39QTVHGbl2uvdFg0wO9ChcG4D6seJRffCR1eZZJqS1Vt97kL3k3kUIXaPIswi5aasyTpajevkxesJvngDrNTtLM7+vsXRWSkGH0rAgMBAAECgYAlnFEQnP7RNlyTX4E95Kqy1AnjlWoVN8adoiU9bfUkpD7nA0jcdLNzIGFZZBvYKysd3m0ml1ISdddSLTpRjSl8K6O9dJDud3G9Oh3qCGgFflcKuKEXDnlaooX1sBrWF5vS0Gvg98x2C52Pnblm2eGVuTvCMaINDZLaamUlaFldMQJBAO3clhAIBJSWlm7Tt/a1d7+IbsGcS16Rk/N23DHg6LADXxIezxgSrpztSa5Nq81W5RC2WsotYYeRt+8KHsPRRn8CQQDfHa7A7hBTOT/V4FXTApuJUlReUh6cHWPsrxf/rUYKylK9WYBAJv1AZW9KaRtcadyu7ldNMb3MAsbE2vLoW2tVAkEAxhvLAF8tMXSapoO/3MMXkXbYiHjcbU9iooyEqSZhpven3ze51Jr6w8j+bSZTyRpufpTi2TEi4f8D6xvKs91BkQJBAKLS05xiX7GMfwSDQb7LEVzmo0FuJn6BiFHK+fWRqyLmwfkDHvAyQ/FB1TT1fY00iGN09msUWNFQWWSB8HEXfj0CQQCAJYV35rNJ781DXhBH5m1tq74zDNzAqynjm0hqhzlVMSHTYFIeU6SBnhk3swnfvJ8kgy3bQJtohYZ8Tuaz19VN";
            String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALCMKte9/clarVwbCvsLJfN9QeiWopR3DIhvwxBQwIkU49PMoHXDIUBpw6iC9IHdeQBRP8z1BMOwiZgtGTshKKNBd6RdwgQrCp6PxNWw5o0inRMhMCYBBy6xek+4ilVrX2rc9OkDOAS0Z1btkqKqJ6ibxDdTTStdT4J2oqAloTvlAgMBAAECgYBhANL1cV3FSb5hEjbJUwnKLHOPQV0ZKARJ3uaVy1jOuRypHhC4Q7u8caBgsXt482BtrTbZ/XJdt10SsQzg8Uoq5m3biRASmuavz+7reYtv6mCYgDu2djUaQ7ocFaH3J5gCPYp8zdXIkuRJ3jzaMPXyiv2wK4vS/gLASyh4dIEMzQJBAOzLeu+VN0DD8/0kpYUASvTWHcaspBPc3nurwNyiAp4ASGi7MHHKVCZ1cCHROm2W/KBlNcCPKlpB0tJw+cl724MCQQC+3ckFcW3gtG3pWOg28NzD9yAA8RJWwZboF5J+ZBdis7crlZBiQs90NcpP64USyFdnEZsOEV8MWrMIfn2CiGZ3AkEA4REKmTu3l6xodPxnAoJjvFDjXlnrXiG5qcx29H5chHb6W+lHw3AvCZrn6Iyov08acQ2hyJOLCtyzmGffU12RJwJAOE3q0B0/AauYRN8CWbrCFVkgasay1z7yinLxtzFFqMtFPKk5V5NH6Ys4rEzZC8pn5jLOX98F//n9mILf+ZLNTwJBAKWH+duqt+3SqbWv4lHh7P/Z8lzSRS6n0p0ma+1vVQl95vY5pcp12GCIniUzKlH7XbZ5S9X5XbGI2inYYsiKGDs=";
            rsaEncrypt.loadPrivateKey(privateKey);
            System.out.println("加载私钥成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("加载私钥失败");
        }

        // 测试字符串
        String encryStr = "1212121212123234234sdfaffgterhkh";
        try {
            System.out.println(new Date());
            // 加密
            byte[] cipher = rsaEncrypt.encrypt(rsaEncrypt.getPublicKey(), encryStr.getBytes());

            // 解密
            byte[] plainText = rsaEncrypt.decrypt(rsaEncrypt.getPrivateKey(), cipher);
            System.out.println(new Date());
            System.out.println(new String(plainText));


            byte[] content = readFileByBytes("C:\\Users\\miracle_8\\Desktop\\数字签名\\数字签名");
            // 签名验证
            byte[] signByte = rsaEncrypt.rsaSign(content, rsaEncrypt.getPrivateKey());
            System.out.println("签名----:" + byteToHex(signByte));
            ByteUtil.saveFile(signByte, "C:\\Users\\miracle_8\\Desktop\\数字签名", "数字签名.sign");
            Boolean isOk = rsaEncrypt.verify(content, signByte, rsaEncrypt.getPublicKey());
            System.out.println("验证:" + isOk);

            // 读取验证文件
            byte[] read = readFileByBytes("C:\\Users\\miracle_8\\Desktop\\数字签名\\数字签名.sign");
            System.out.println("读取签名文件:" + byteToHex(read));
            Boolean isFOk = rsaEncrypt.verify(content, read, rsaEncrypt.getPublicKey());
            System.out.println("文件验证2:" + isFOk);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        rsaEncrypt.genKeyPair();
//        System.out.println("publicKey:" + Base64Utils.encode(rsaEncrypt.getPublicKey().getEncoded()));
//        System.out.println("privateKey:" + Base64Utils.encode(rsaEncrypt.getPrivateKey().getEncoded()));

    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • 435
  • 436
  • 437
  • 438
  • 439
  • 440
  • 441
  • 442
  • 443
  • 444
  • 445
  • 446
  • 447
  • 448
  • 449
  • 450

Base64Utils.java

package com.sm.test1;

import java.io.UnsupportedEncodingException;

/**
 * Base64 加密解密工具类
 *
 * @author miracle_8
 * @date 2019/12/3
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
public class Base64Utils {
    private static char[] base64EncodeChars = new char[]
            { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                    'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
                    '6', '7', '8', '9', '+', '/' };
    private static byte[] base64DecodeChars = new byte[]
            { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,
                    54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
                    12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
                    30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
                    -1, -1, -1 };

    public static String encode(byte[] data) {
        StringBuffer sb = new StringBuffer();
        int len = data.length;
        int i = 0;
        int b1, b2, b3;
        while (i < len) {
            b1 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
                sb.append("==");
                break;
            }
            b2 = data[i++] & 0xff;
            if (i == len) {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
                sb.append("=");
                break;
            }
            b3 = data[i++] & 0xff;
            sb.append(base64EncodeChars[b1 >>> 2]);
            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
            sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
            sb.append(base64EncodeChars[b3 & 0x3f]);
        }
        return sb.toString();
    }

    public static byte[] decode(String str) {
        try {
            return decodePrivate(str);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new byte[]
                {};
    }

    private static byte[] decodePrivate(String str) throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer();
        byte[] data = null;
        data = str.getBytes("US-ASCII");
        int len = data.length;
        int i = 0;
        int b1, b2, b3, b4;
        while (i < len) {
            do {
                b1 = base64DecodeChars[data[i++]];
            } while (i < len && b1 == -1);
            if (b1 == -1) {
                break;

            }
            do {
                b2 = base64DecodeChars[data[i++]];
            } while (i < len && b2 == -1);
            if (b2 == -1) {
                break;
            }
            sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));

            do {
                b3 = data[i++];
                if (b3 == 61) {
                    return sb.toString().getBytes("iso8859-1");
                }
                b3 = base64DecodeChars[b3];
            } while (i < len && b3 == -1);
            if (b3 == -1) {
                break;
            }
            sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
            do {
                b4 = data[i++];
                if (b4 == 61) {
                    return sb.toString().getBytes("iso8859-1");
                }
                b4 = base64DecodeChars[b4];
            } while (i < len && b4 == -1);
            if (b4 == -1) {
                break;
            }
            sb.append((char) (((b3 & 0x03) << 6) | b4));
        }
        return sb.toString().getBytes("iso8859-1");
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116

***ByteUtil.java ***

package com.sm.test1;

import java.io.*;

/**
 * byte数组工具类实现byte[]与文件之间的相互转换
 *
 * @author miracle_8
 * @date 2019/12/3
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
public class ByteUtil {
    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 根据byte数组,生成文件
     *
     * @param
     * @return
     * @date 2019/12/3
     * @author miracle_8
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static void saveFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            // 判断文件目录是否存在
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }

            file = new File(filePath + "\\" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82

linux用openssl实现公钥和私钥

  1. 验证openssl:
 rpm -qa | grep openssl
  • 1

在这里插入图片描述
2. yum安装openssl

 yum -y install openssl openssl-devel
  • 1

在这里插入图片描述
3. 生成RSA私钥:

openssl -> genrsa -out rsa_private_key.pem 1024
  • 1

在这里插入图片描述
此时我们就可以在当前路径下看到rsa_private_key.pem文件了,如下所示:
在这里插入图片描述
4. 把RSA私钥转换成PKCS8格式:

pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt 
  • 1

在这里插入图片描述
5. 生成RSA公钥:

rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
  • 1

在这里插入图片描述
可以看到一个文件名为rsa_public_key.pem的文件,打开它,可以看到-----BEGIN PUBLIC KEY-----开头,-----END PUBLIC KEY-----结尾的没有换行的字符串,这个就是公钥:
在这里插入图片描述

附:ssh格式的公钥

ssh-keygen -t rsa -f key
ssh-keygen -e -f key.pub > key_ss2.pub 
  • 1
  • 2

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/408983
推荐阅读
相关标签
  

闽ICP备14008679号