两种方式生成RSA 公钥私钥

两种方式-生成RSA256私钥公钥

两种方式生成私钥公钥

1.ssh-keygen 方式

  • 生成加密长度4096位密钥 

    生成私钥:ssh-keygen -t rsa -b 4096 -f ${private}.key

    生成公钥:openssl rsa -in ${private}.key -pubout -outform PEM -out ${public}.key.pub

    转换格式:openssl pkcs8 -topk8 -inform PEM -in jwtRS256.key -outform pem -nocrypt -out pkcs8.pem

  • 生成加密长度1024位密钥

    生成私钥:ssh-keygen -t rsa -b 1024 -f ${private}.key

    生成公钥:openssl rsa -in ${private}.key -pubout -outform PEM -out ${public}.key.pub

    转换格式:openssl pkcs8 -topk8 -inform PEM -in jwtRS256.key -outform pem -nocrypt -out pkcs8.pem

2.openssl方式

  • 生成加密长度1024位密钥

    生成私钥:openssl genrsa -out rsaprivatekey.pem 1024

    生成公钥:openssl rsa -in rsaprivatekey.pem -out rsapublickey.pem -pubout

    转换格式:openssl pkcs8 -topk8 -in rsaprivatekey.pem -out pkcs8rsaprivate_key.pem -nocrypt

最大加密明文长度为117位,最大解密密文128位

比如:需要加密String param = “id=1&name=张三”,实际上只能加密到:id=1&name. 

使用一对1024位密钥私钥-加密后得到密文:[[email protected]

解密也只能按照128位:[[email protected] 将1024位公钥解密后 得到id=1&name 

我这里使用的公私钥分别为:

publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCr1CJfUouPBVoGAnoxUd2Uj8MZ\n" +
        "NFvFSBYNlK74zwQxFsPXhNq2ba3JQCwV6P35cNqEK2htaG+phr/Gy+3YVQWl1Tau\n" +
        "5bVbsWCkwO+5EHdx9dN1IfUUO9Y9NDarUxYyeBOvtfc2I/bA5xwPkskRMzBKWbp1\n" +
        "kC9AxstNiOoJnUNF3wIDAQAB";

privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKvUIl9Si48FWgYC\n" +
        "ejFR3ZSPwxk0W8VIFg2UrvjPBDEWw9eE2rZtrclALBXo/flw2oQraG1ob6mGv8bL\n" +
        "7dhVBaXVNq7ltVuxYKTA77kQd3H103Uh9RQ71j00NqtTFjJ4E6+19zYj9sDnHA+S\n" +
        "yREzMEpZunWQL0DGy02I6gmdQ0XfAgMBAAECgYEAkFVO0hc6V1a9edLW5VrI76Oa\n" +
        "1C8g7yRQMfQ0zZbHBJ0EwKI+PYL/uc8HuRfPTpo3U1JLE6voL9SaftiJ32/7nyJv\n" +
        "5ij6Yy+aX2q93oU9Y+9AZ9ottynY5X2pDwhVtw87ESa/zSGVjq+6fkc9+3FsmnKi\n" +
        "XCbyKN2d0RAITaMyQpECQQDXnAwdSzFubmLyoKoRsMiNckvGH6lDjykvjbhBkTCy\n" +
        "E8AVkxI0F9Kk5UTMLqCJyd1D7tCQuLkWu4IT+cZoA6oVAkEAzAR+MKm5kNT28Jzm\n" +
        "JqX0i2nX3SR1LLbf+oKqM2X21z4XJVIbZH9iTlYpwU9ctvENfMl26p5r3HzXb8xY\n" +
        "UqExIwJBAJGqntCnvYTDVVxgyaXcDxLpFmKLf3riXMwA7mx14DVffJXW4CSLt8eq\n" +
        "Efn0wod092VvEj/EXWALXM2MIcyiNSUCQFlZhmKNkoWJn3SVYn5+o/ECs9VYCDFD\n" +
        "DijKXPwRpd9yg/SGVxTWbRldxv+wYCyGuZ9zJC9wnlB8JGYEGpJlof0CQQCg2wrN\n" +
        "iXhlPca0KboggdqThdESAdpINS5lq4ZhZDpIlUY7HmZCG/VdXXPnd4U4JAsBJhS6\n" +
        "uglcCks44QIDM9D6";

密钥可分为1024,2048,4096等位密钥,位数不同,可加解密明文长度不一。 比如1024位密钥: 可加解密明文长度 len = 1024/8 – 11 = 117字节。

点赞