java - 在没有库的情况下读取 Java 中的 PKCS#1 或 SPKI 公钥

标签 java encryption public-key-encryption java-security

我需要使用公钥来验证Java中的某些数据,但我似乎无法以Java无需第三方插件即可使用的方式格式化 key 。

我使用 Node.js 的 crypto 库生成 key ,它让我可以选择 PKCS#1SPKI,并且.pem 或 .der 文件格式。

我听说 Java 不支持开箱即用的 PKCS#1,并且 StackOverflow 上的几乎所有其他答案都建议使用 BouncyCaSTLe 或类似的,但就我而言,我我正在编写一个 SDK,并且根本无法使用库来读取此公钥。

因此,我目前正在读取 .der 格式的 key ,因为这样可以节省剥离 PEM header 并从 Base-64 解码 key 的麻烦。当我运行这个时,我收到错误:

java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0000be:ASN.1 encoding routines:OPENSSL_internal:WRONG_TAG

这就是我所拥有的(抱歉,它是用 Kotlin 编写的,而不是像标题所暗示的那样用 Java 编写的)

// Here's a key for convenience
val key = Base64.getDecoder().decode("MFUCTgF/uLsPBS13Gy7C3dPpiDF6SYCLUyyl6CFqPtZT1h5bwKR9EDFLQjG/kMiwkRMcmEeaLKe5qdj9W/FfFitwRAm/8F53pQw2UETKQI2b2wIDAQAB");

val keySpec = X509EncodedKeySpec(key)
val keyFactory = KeyFactory.getInstance("RSA")
val publicKey = keyFactory.generatePublic(keySpec) // error thrown here

val cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding")
cipher.init(Cipher.DECRYPT_MODE, publicKey)

我目前最好的想法是在 Node.js 端安装一个库,这样问题较少,以支持将 key 导出为 PKCS#8,但我想我应该先检查一下我是否缺少任何东西。

最佳答案

以下代码将 PKCS#1 编码的公钥转换为SubjectPublicKeyInfo 编码的公钥,这是 RSA KeyFactory 使用 X509EncodedKeySpec 接受的公钥编码 - 如下subjectPublicKeyInfo 在 X.509 规范中定义。

基本上它是一种低级 DER 编码方案

  1. 将 PKCS#1 编码 key 包装成一个位字符串(标记 0x03,以及未使用位数的编码,一个值为 0x00 的字节);<
  2. 在前面添加 RSA 算法标识符序列(RSA OID + 空参数) - 预编码为字节数组常量;
  3. 最后将它们放入一个序列中(标签0x30)。

没有使用任何库。实际上,对于createSubjectPublicKeyInfoEncoding,甚至不需要导入语句。

<小时/>
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class PKCS1ToSubjectPublicKeyInfo {

    private static final int SEQUENCE_TAG = 0x30;
    private static final int BIT_STRING_TAG = 0x03;
    private static final byte[] NO_UNUSED_BITS = new byte[] { 0x00 };
    private static final byte[] RSA_ALGORITHM_IDENTIFIER_SEQUENCE =
            {(byte) 0x30, (byte) 0x0d,
                    (byte) 0x06, (byte) 0x09, (byte) 0x2a, (byte) 0x86, (byte) 0x48, (byte) 0x86, (byte) 0xf7, (byte) 0x0d, (byte) 0x01, (byte) 0x01, (byte) 0x01,
                    (byte) 0x05, (byte) 0x00};


    public static RSAPublicKey decodePKCS1PublicKey(byte[] pkcs1PublicKeyEncoding)
            throws NoSuchAlgorithmException, InvalidKeySpecException
    {
        byte[] subjectPublicKeyInfo2 = createSubjectPublicKeyInfoEncoding(pkcs1PublicKeyEncoding);
        KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");
        RSAPublicKey generatePublic = (RSAPublicKey) rsaKeyFactory.generatePublic(new X509EncodedKeySpec(subjectPublicKeyInfo2));
        return generatePublic;
    }

    public static byte[] createSubjectPublicKeyInfoEncoding(byte[] pkcs1PublicKeyEncoding)
    {
        byte[] subjectPublicKeyBitString = createDEREncoding(BIT_STRING_TAG, concat(NO_UNUSED_BITS, pkcs1PublicKeyEncoding));
        byte[] subjectPublicKeyInfoValue = concat(RSA_ALGORITHM_IDENTIFIER_SEQUENCE, subjectPublicKeyBitString);
        byte[] subjectPublicKeyInfoSequence = createDEREncoding(SEQUENCE_TAG, subjectPublicKeyInfoValue);

        return subjectPublicKeyInfoSequence;
    }

    private static byte[] concat(byte[] ... bas)
    {
        int len = 0;
        for (int i = 0; i < bas.length; i++)
        {
            len += bas[i].length;
        }

        byte[] buf = new byte[len];
        int off = 0;
        for (int i = 0; i < bas.length; i++)
        {
            System.arraycopy(bas[i], 0, buf, off, bas[i].length);
            off += bas[i].length;
        }

        return buf;
    }

    private static byte[] createDEREncoding(int tag, byte[] value)
    {
        if (tag < 0 || tag >= 0xFF)
        {
            throw new IllegalArgumentException("Currently only single byte tags supported");
        }

        byte[] lengthEncoding = createDERLengthEncoding(value.length);

        int size = 1 + lengthEncoding.length + value.length;
        byte[] derEncodingBuf = new byte[size];

        int off = 0;
        derEncodingBuf[off++] = (byte) tag;
        System.arraycopy(lengthEncoding, 0, derEncodingBuf, off, lengthEncoding.length);
        off += lengthEncoding.length;
        System.arraycopy(value, 0, derEncodingBuf, off, value.length);

        return derEncodingBuf;
    }   

    private static byte[] createDERLengthEncoding(int size)
    {
        if (size <= 0x7F)
        {
            // single byte length encoding
            return new byte[] { (byte) size };
        }
        else if (size <= 0xFF)
        {
            // double byte length encoding
            return new byte[] { (byte) 0x81, (byte) size };
        }
        else if (size <= 0xFFFF)
        {
            // triple byte length encoding
            return new byte[] { (byte) 0x82, (byte) (size >> Byte.SIZE), (byte) size };
        }

        throw new IllegalArgumentException("size too large, only up to 64KiB length encoding supported: " + size);
    }

    public static void main(String[] args) throws Exception
    {
        // some weird 617 bit key, which is way too small and not a multiple of 8
        byte[] pkcs1PublicKeyEncoding = Base64.getDecoder().decode("MFUCTgF/uLsPBS13Gy7C3dPpiDF6SYCLUyyl6CFqPtZT1h5bwKR9EDFLQjG/kMiwkRMcmEeaLKe5qdj9W/FfFitwRAm/8F53pQw2UETKQI2b2wIDAQAB");
        RSAPublicKey generatePublic = decodePKCS1PublicKey(pkcs1PublicKeyEncoding);
        System.out.println(generatePublic);
    }
}
<小时/>

注释:

  • NoSuchAlgorithmException 可能应该被捕获并放入 RuntimeException 中;
  • 私有(private)方法createDERLengthEncoding可能不应该接受负大小。
  • 尚未测试较大的 key ,请验证这些 key 的 createDERLengthEncoding - 我认为它可以工作,但最好是安全而不是后悔。

关于java - 在没有库的情况下读取 Java 中的 PKCS#1 或 SPKI 公钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54238568/

相关文章:

java - JPA 查询为不同的参数返回相同的结果

ruby-on-rails - 公司在 ActiveRecord/Ruby on Rails 网络应用程序中对加密进行代码审查?

java - 输出流中缺少数字(包含完整详细信息)

c++ - 加密/解密 SQLite 数据库并使用它 "on the fly"

public-key-encryption - 私钥/公钥 ssh-keygen -t rsa

java - 从 JAR 中获取 File 对象的任何方法

java - JMeter 测试中 CXF 的不连贯行为

java - 无法启动部署在 websphere 8.5.5 上的 springboot 应用程序

javascript - 我应该如何加密 API 访问的密码而不向客户端展示算法?

php - 如何使用 php 和 mysql 处理加密的私有(private)消息