【问题标题】:Using openssh public key (ecdsa-sha2-nistp256) with Java Security使用带有 Java 安全性的 openssh 公钥 (ecdsa-sha2-nistp256)
【发布时间】:2017-12-02 03:38:01
【问题描述】:

是否有 Java 库/示例可以读取 Java 中 JCE PublicKey 的 openssh 格式 ecdsa 公钥?我想为JWT 使用EC。

我尝试读取的格式是根据 authorized_keys 或 Github API(例如https://api.github.com/users/davidcarboni/keys):ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBK8hPtB72/sfYgNw1WTska2DNOJFx+QhUxuV6OLINSD2ty+6gxcM8yZrvMqWdMePGRb2cGh8L/0bGOk+64IQ/pM=

我找到了这个答案,它适用于 RSA 和 DSS: Using public key from authorized_keys with Java security,以及有关 ECDSA 的 openssh 格式的讨论:https://security.stackexchange.com/questions/129910/ecdsa-why-do-ssh-keygen-and-java-generated-public-keys-have-different-sizes

但是,我在尝试为 ECDSA 调整 RSS/DSA 代码时迷失了方向 - 我不确定如何设置 ECPublicKeySpec。它需要ECPoint、EllipticCurve、ECParameterSpec、ECField。 openssh 格式只包含两个整数,这对ECPoint 有意义,但我不知道如何设置其余的。

我一直在寻找一堆库,包括jsch、sshj、ssh-tools 和老旧的Bouncycastle。我最接近的是:

com.jcraft.jsch.KeyPair load = com.jcraft.jsch.KeyPair.load(jsch, null, bytes[openSshKey]);

这很好地加载了密钥,但没有让我使用 JCE PublicKey - 只是一个 byte[] getPublicKeyBlob() 方法。

我是否遗漏了一些明显的东西?

【问题讨论】:

  • 我在使用com.nimbusds.jose.jwk.ECKey 设置ECPublicKeySpec 方面取得了一些进展。这提供了一个ECKey.Curve.P_256.toECParameterSpec() 调用,它可以整理出大部分的神秘参数。这只是留下了ECPoint,因此看起来更有可能适应 RSA/DSA 示例。
  • 所以,好吧,很有趣。我正在调整 RSA/DSA 示例并获得值“ecdsa-sha2-nistp256”、“nistp256”,然后只有一个 BigInt(而不是两个)。我想知道这是否只是“公共部分”,因为它是一个公钥?我想是时候阅读RFC 5656, section 3.1了。

标签: java openssh jce elliptic-curve ecdsa


【解决方案1】:

我找到了一种使用 Bouncycastle 的方法(但想找到一种 JCE 方法)。

改编自Using public key from authorized_keys with Java security的代码,并引用RFC 5656, section 3.1,添加到decodePublicKey的以下块将解析单个BigInt值Q,即“从椭圆曲线点编码的公钥”:

if (type.startsWith("ecdsa-sha2-") &&
            (type.endsWith("nistp256") || type.endsWith("nistp384") || type.endsWith("nistp521"))) {

        // Based on RFC 5656, section 3.1 (https://www.rfc-editor.org/rfc/rfc5656#section-3.1)

        // The string [identifier] is the identifier of the elliptic curve
        // domain parameters.  The format of this string is specified in
        // Section 6.1 (https://www.rfc-editor.org/rfc/rfc5656#section-6.1).
        // Information on the REQUIRED and RECOMMENDED sets of
        // elliptic curve domain parameters for use with this algorithm can be
        // found in Section 10 (https://www.rfc-editor.org/rfc/rfc5656#section-10).
        String identifier = decodeType();
        if (!type.endsWith(identifier)) {
            throw new IllegalArgumentException("Invalid identifier " + identifier + " for key type " + type + ".");
        }

        // Q is the public key encoded from an elliptic curve point into an
        // octet string as defined in Section 2.3.3 of [SEC1];
        // (https://www.rfc-editor.org/rfc/rfc5656#ref-SEC1)
        // point compression MAY be used.
        BigInteger q = decodeBigInt();

        ECPublicKey keyBC = getKeyBC(q, identifier);
        return keyBC;
    }

我发现从 Q 到 ECPublicKey 的解决方案如下,使用 Bouncycastle API(感谢 Generate ECPublicKey from ECPrivateKey 提供起点):

ECPublicKey getKeyBC(BigInteger q, String identifier) {
    // https://stackoverflow.com/questions/42639620/generate-ecpublickey-from-ecprivatekey
    try {
        // This only works with the Bouncycastle library:
        Security.addProvider(new BouncyCastleProvider());
        // http://www.bouncycastle.org/wiki/pages/viewpage.action?pageId=362269#SupportedCurves(ECDSAandECGOST)-NIST(aliasesforSECcurves)
        String name = identifier.replace("nist", "sec") + "r1";
        KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
        ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(name);
        ECPoint point = ecSpec.getCurve().decodePoint(q.toByteArray());
        ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec);
        ECPublicKey publicKey = (ECPublicKey) keyFactory.generatePublic(pubSpec);
        return publicKey;
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException e) {
        throw new RuntimeException(e);
    }
}

这使您可以从 openssh 格式的椭圆曲线公钥 (ssh-keygen -t ecdsa -b [256|384|521]) 转换为 JCE ECPublicKey。

【讨论】:

【解决方案2】:

为了完整起见,这是我使用的代码。它几乎是纯 JCE,在辅助方法中添加了一些 Bouncycastle(这更新了 Using public key from authorized_keys with Java security 中的示例代码):

...
        } else if (type.startsWith("ecdsa-sha2-") &&
                (type.endsWith("nistp256") || type.endsWith("nistp384") || type.endsWith("nistp521"))) {
            // Based on RFC 5656, section 3.1 (https://tools.ietf.org/html/rfc5656#section-3.1)
            String identifier = decodeType();
            BigInteger q = decodeBigInt();
            ECPoint ecPoint = getECPoint(q, identifier);
            ECParameterSpec ecParameterSpec = getECParameterSpec(identifier);
            ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParameterSpec);
            return KeyFactory.getInstance("EC").generatePublic(spec);
        } ...

/**
 * Provides a means to get from a parsed Q value to the X and Y point values.
 * that can be used to create and ECPoint compatible with ECPublicKeySpec.
 *
 * @param q          According to RFC 5656:
 *                   "Q is the public key encoded from an elliptic curve point into an octet string"
 * @param identifier According to RFC 5656:
 *                   "The string [identifier] is the identifier of the elliptic curve domain parameters."
 * @return An ECPoint suitable for creating a JCE ECPublicKeySpec.
 */
ECPoint getECPoint(BigInteger q, String identifier) {
    String name = identifier.replace("nist", "sec") + "r1";
    ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(name);
    org.bouncycastle.math.ec.ECPoint point = ecSpec.getCurve().decodePoint(q.toByteArray());
    BigInteger x = point.getAffineXCoord().toBigInteger();
    BigInteger y = point.getAffineYCoord().toBigInteger();
    System.out.println("BC x = " + x);
    System.out.println("BC y = " + y);
    return new ECPoint(x, y);
}

/**
 * Gets the curve parameters for the given key type identifier.
 *
 * @param identifier According to RFC 5656:
 *                   "The string [identifier] is the identifier of the elliptic curve domain parameters."
 * @return An ECParameterSpec suitable for creating a JCE ECPublicKeySpec.
 */
ECParameterSpec getECParameterSpec(String identifier) {
    try {
        // http://www.bouncycastle.org/wiki/pages/viewpage.action?pageId=362269#SupportedCurves(ECDSAandECGOST)-NIST(aliasesforSECcurves)
        String name = identifier.replace("nist", "sec") + "r1";
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
        parameters.init(new ECGenParameterSpec(name));
        return parameters.getParameterSpec(ECParameterSpec.class);
    } catch (InvalidParameterSpecException | NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Unable to get parameter spec for identifier " + identifier, e);
    }
}

【讨论】:

  • 我能说服你在 github 上分享你的项目吗?我担心我看似相同的问题会被标记为您的重复问题,并且对密码学的理解有限。谢谢 - 克里斯
  • 很高兴代码在 Github 上是可见的,至少现在是这样:github.com/rosgovuk/discharges-jwt/blob/master/src/main/java/uk/… 我会备份以防万一,请随时询问它是否会消失。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-01
  • 2011-04-01
  • 2022-01-06
  • 2016-02-05
  • 2016-07-15
  • 1970-01-01
  • 2019-05-19
相关资源
最近更新 更多