当前位置: 首页 > 知识库问答 >
问题:

Javassh-rsa字符串为公钥

淳于祺
2023-03-14

我想得到一个. pub文件内容的公钥,这是一个. pub文件内容看起来像什么的例子(用ssh-keygen生成):

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDBPL2s+25Ank3zS6iHUoVk0tS63dZM0LzAaniiDon0tdWwq4vcL4+fV8BsAEcpMeijS92JhDDc9FccXlHbdDcmd6c4ITOt9h9xxhIefGsi1FTVJ/EjVtbqF5m0bu7ruIMGvuP1p5s004roHx9y0UdHvD/yNWLISMhy4nio6jLailIj3FS53Emj1WRNsOrpja3LzPXzhuuj6YnD9yfByT7iGZipxkmleaXrknChPClLI9uhcqtAzBLdd0NVTJLOt/3+d1cSNwdBw9e53wJvpEmH+P8UOZd+oV/y7cHIej4jQpBXVvpJR1Yaluh5RuxY90B0hSescUAj4g/3HVPpR/gE7op6i9Ab//0iXF15uWGlGzipI4lA2/wYEtv8swTjmdCTMNcTDw/1huTDEzZjghIKVpskHde/Lj416c7eSByLqsMg2OhlZGChKznpIjhuNRXz93DwqKuIKvJKSnhqaJDxmDGfG7nlQ/eTwGeAZ6VR50yMPiRTIpuYd767+Nsg486z7p0pnKoBlL6ffTbfeolUX2b6Nb9ZIOxJdpCSNTQRKQ50p4Y3S580cUM1Y2EfjlfIQG1JdmTQYB75AZXi/cB2PvScmF0bXRoj7iHg4lCnSUvRprWA0xbwzCW/wjNqw6MyRX42FFlvSRrmfaxGZxKYbmk3TzBv+Fp+CADPqQm3OQ== test@test.com

如果我是对的,这不是公钥,但是可以从这个字符串中获取公钥。

这个答案回答了我的问题https://stackoverflow.com/a/19387517/2735398
但答案似乎不起作用。我有个例外:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format

当看到答案的评论时,我不是唯一有问题的人...

如何修复异常?或者有没有其他方法可以从字符串中获取公钥?

共有3个答案

颜昕
2023-03-14

我找到了很多关于如何获取公钥的答案——但实际上没有一个答案包含如何将openssh公钥作为字符串获取的部分——它有一种特殊的格式。

敬上@Jcs和@James K Polk

这取决于BouncyCastle。它可能不需要。

package cuul.stuff;

import lombok.SneakyThrows;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.BCRSAPrivateCrtKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Security;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Base64;

/**
 * Takes an private SSH key and cranks out the corresponding public one.
 *
 * Just what this command would have done: <pre>ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub</pre>
 *
 * @link https://stackoverflow.com/questions/3706177/how-to-generate-ssh-compatible-id-rsa-pub-from-java
 * @link https://stackoverflow.com/questions/7216969/getting-rsa-private-key-from-pem-base64-encoded-private-key-file/7221381#7221381
 *
 * Why - because I can.
 */
public class ExtractPublicFromPrivateSshKey {

    private static final String BEGIN_RSA_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n";
    private static final String END_RSA_PRIVATE_KEY = "-----END RSA PRIVATE KEY-----";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    @SneakyThrows
    public static String extract(String privateKeyString) {
        if (!privateKeyString.startsWith(BEGIN_RSA_PRIVATE_KEY)) {
            throw new InvalidKeySpecException("Can only extract public key from a RSA private. "
                    + "This is not an RSA key (header should have been '" + BEGIN_RSA_PRIVATE_KEY + "'");
        }

        privateKeyString = privateKeyString.replace(BEGIN_RSA_PRIVATE_KEY, "");
        privateKeyString = privateKeyString.replace(END_RSA_PRIVATE_KEY, "");
        privateKeyString = privateKeyString.trim();

        byte[] privateKeyBytes = Base64.getMimeDecoder().decode(privateKeyString);

        BCRSAPrivateCrtKey rsaPrivateKey = (BCRSAPrivateCrtKey) getPrivate(privateKeyBytes);

        //create a KeySpec and let the Factory due the Rest. You could also create the KeyImpl by your own.
        RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(
                new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent()));

        byte[] bytes = encodePublicKey(publicKey);
        return "ssh-rsa " + new String(Base64.getEncoder().encode(bytes), StandardCharsets.UTF_8) + " some@user";
    }

    private static PrivateKey getPrivate(byte[] privateKeyBytes)
            throws Exception {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    }

    /**
     * @link https://stackoverflow.com/questions/3706177/how-to-generate-ssh-compatible-id-rsa-pub-from-java
     *
     * The key format used by ssh is defined in the RFC #4253. The format for RSA public key is the following :

     * string    "ssh-rsa"
     * mpint     e  // key public exponent
     * mpint     n  // key modulus
     *
     * All data type encoding is defined in the section #5 of RFC #4251. string and mpint (multiple precision integer) types are encoded this way :
     *
     * 4-bytes word: data length (unsigned big-endian 32 bits integer)
     * n bytes     : binary representation of the data
     *
     * or instance, the encoding of the string "ssh-rsa" is:
     *
     * byte[] data = new byte[] {0, 0, 0, 7, 's', 's', 'h', '-', 'r', 's', 'a'};
     */
    private static byte[] encodePublicKey(RSAPublicKey key) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        /* encode the "ssh-rsa" string */
        byte[] sshrsa = new byte[] {0, 0, 0, 7, 's', 's', 'h', '-', 'r', 's', 'a'};
        out.write(sshrsa);
        /* Encode the public exponent */
        BigInteger e = key.getPublicExponent();
        byte[] data = e.toByteArray();
        encodeUInt32(data.length, out);
        out.write(data);
        /* Encode the modulus */
        BigInteger m = key.getModulus();
        data = m.toByteArray();
        encodeUInt32(data.length, out);
        out.write(data);
        return out.toByteArray();
    }

    private static void encodeUInt32(int value, OutputStream out) throws IOException {
        byte[] tmp = new byte[4];
        tmp[0] = (byte)((value >>> 24) & 0xff);
        tmp[1] = (byte)((value >>> 16) & 0xff);
        tmp[2] = (byte)((value >>> 8) & 0xff);
        tmp[3] = (byte)(value & 0xff);
        out.write(tmp);
    }
}
翟柏
2023-03-14

您必须将密钥转换为pkcs8规范。请使用下面的命令

ssh-keygen -f private.key -e -m pkcs8 > test-pkcs8.pub

然后转换成x509

openssl rsa -pubin -in test-pkcs8.pub -outform pem > test-x509.pem

然后,您可以使用下面的代码将公钥作为Java中的公钥读取

import java.io.IOException;

import java.net.URISyntaxException;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.security.KeyFactory;

import java.security.NoSuchAlgorithmException;

import java.security.PrivateKey;

import java.security.interfaces.RSAPublicKey;

import java.security.spec.InvalidKeySpecException;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import java.util.Base64;


/**

* This file is intended to be used on a IDE for testing purposes.

* ClassLoader.getSystemResource won't work in a JAR

*/

public class Main {


    public static void main(String[] args) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, URISyntaxException {


        String privateKeyContent = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("private_key_pkcs8.pem").toURI())));

        String publicKeyContent = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("public_key.pem").toURI())));


        privateKeyContent = privateKeyContent.replaceAll("\\n", "").replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "");

        publicKeyContent = publicKeyContent.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");;


        KeyFactory kf = KeyFactory.getInstance("RSA");


        PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyContent));

        PrivateKey privKey = kf.generatePrivate(keySpecPKCS8);


        X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyContent));

        RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(keySpecX509);


        System.out.println(privKey);

        System.out.println(pubKey);

    }

}

从下面的两个链接中得到答案

在Java中将ssh rsa转换为X509规范

在Java中加载X509规范密钥作为RSAPublicKey对象

希望这能给你一些直觉。

符学
2023-03-14

这是我的SSH RSA-

public class CertificateUtils {
    private static final int VALUE_LENGTH = 4;
    private static final byte[] INITIAL_PREFIX = new byte[]{0x00, 0x00, 0x00, 0x07, 0x73, 0x73, 0x68, 0x2d, 0x72, 0x73, 0x61};
    private static final Pattern SSH_RSA_PATTERN = Pattern.compile("ssh-rsa[\\s]+([A-Za-z0-9/+]+=*)[\\s]+.*");

// SSH-RSA key format
//
//        00 00 00 07             The length in bytes of the next field
//        73 73 68 2d 72 73 61    The key type (ASCII encoding of "ssh-rsa")
//        00 00 00 03             The length in bytes of the public exponent
//        01 00 01                The public exponent (usually 65537, as here)
//        00 00 01 01             The length in bytes of the modulus (here, 257)
//        00 c3 a3...             The modulus

    public static RSAPublicKey parseSSHPublicKey(String key) throws InvalidKeyException {
        Matcher matcher = SSH_RSA_PATTERN.matcher(key.trim());
        if (!matcher.matches()) {
            throw new InvalidKeyException("Key format is invalid for SSH RSA.");
        }
        String keyStr = matcher.group(1);

        ByteArrayInputStream is = new ByteArrayInputStream(Base64.decodeBase64(keyStr));

        byte[] prefix = new byte[INITIAL_PREFIX.length];

        try {
            if (INITIAL_PREFIX.length != is.read(prefix) || !ArrayUtils.isEquals(INITIAL_PREFIX, prefix)) {
                throw new InvalidKeyException("Initial [ssh-rsa] key prefix missed.");
            }

            BigInteger exponent = getValue(is);
            BigInteger modulus = getValue(is);

            return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, exponent));
        } catch (IOException | InvalidKeySpecException | NoSuchAlgorithmException e) {
            throw new InvalidKeyException("Failed to read SSH RSA certificate from string", e);
        }
    }

    private static BigInteger getValue(InputStream is) throws IOException {
        byte[] lenBuff = new byte[VALUE_LENGTH];
        if (VALUE_LENGTH != is.read(lenBuff)) {
            throw new InvalidParameterException("Unable to read value length.");
        }

        int len = ByteBuffer.wrap(lenBuff).getInt();
        byte[] valueArray = new byte[len];
        if (len != is.read(valueArray)) {
            throw new InvalidParameterException("Unable to read value.");
        }

        return new BigInteger(valueArray);
    }
}

希望这有帮助。

 类似资料:
  • 我有一个RSA公钥证书。我可以使用具有。PEM扩展名或仅将其用作具有以下格式的字符串: 启动RSA公共密钥 {KEY} -----结束RSA公钥----- 我试图使用此密钥向服务器发送加密的JSON。我尝试了许多其他相关堆栈溢出问题的解决方案,但没有一个答案不适合我。这个答案似乎有道理https://stackoverflow.com/a/43534042,但有些东西不能正常工作,可能是因为X50

  • 如何使用作为字符串提供的公共和私有RSA密钥进行加密和解密。因为我正在使用RSACryptoServiceProvider,它需要XML格式,所以是否有可能使用提供的字符串。谢谢。

  • 我正在尝试将RsaKeyParameter公钥保存到SQL数据库中。我得到一个错误,Bouncy Castle不能将RsaKeyParameters转换为字节。 使用BouncyCastle C#。 但它不喜欢ToAsn1Object。只是为了补充这是一个例子,我知道我的变量名是不同的。 公钥应该是字节,然后是字符串,保存到数据库中。

  • 出于明显的安全原因,我需要用RSA私钥和公钥加密和解密用户的PIN码,我找到了工作解决方案,看起来像: 一切正常,但在本例中,键对不是静态的,每次都会生成新值,但我需要使用相同的键,它们表示为字符串变量: 有没有办法将这些变量强制转换为PublicKey和PrivateKey类?

  • 如何从Go中的字符串导入RSA公钥,以便用于加密数据? 我的程序应该执行以下操作: > 接收一个用Base64编码的公钥 将此公钥从Base64解码为字节 导入公钥,以便Go的RSA实现可以使用(问题在这个阶段) 加密AES密钥: 提前谢谢! 解决方案: 公钥必须使用crypto/x509包进行解码。 例如: 然后可以使用带有RSA的进行加密。

  • 问题内容: 因此,我正在使用Spongy Castle(Android)为RSA公钥生成PEM编码的字符串,并将其上传到服务器。这是我目前正在做的: 现在,您可能已经知道,我不确定如何构造或是否有更简单的方法来执行此操作。 当使用Bouncy Case时,我曾经这样做过 但是由于某种原因,海绵城堡中不存在PEMWriter类 问题答案: 好的,这可能不是最聪明的方法(或者也许是?),但是在检查了此