椭圆曲线公钥的Java紧凑表示

qcbq4gxm  于 2022-12-25  发布在  Java
关注(0)|答案(6)|浏览(140)

java.security.PublicKey#getEncoded()返回密钥的X509表示,在ECC的情况下,与原始ECC值相比增加了大量开销。
我希望能够在最紧凑的表示(即尽可能小的字节块)中将PublicKey转换为字节数组(反之亦然)。
密钥类型(ECC)和具体曲线类型是预先已知的,因此关于它们的信息不需要被编码。
解决方案可以使用Java API、BouncyCastle或任何其他自定义代码/库(只要许可证不意味着需要开放将使用它的专有代码)。

xu3bshqb

xu3bshqb1#

Bouncy Castle中也提供了此功能,但我将展示如何仅使用Java完成此操作,以防有人需要它:

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.util.Arrays;

public class Curvy {

    private static final byte UNCOMPRESSED_POINT_INDICATOR = 0x04;

    public static ECPublicKey fromUncompressedPoint(
            final byte[] uncompressedPoint, final ECParameterSpec params)
            throws Exception {

        int offset = 0;
        if (uncompressedPoint[offset++] != UNCOMPRESSED_POINT_INDICATOR) {
            throw new IllegalArgumentException(
                    "Invalid uncompressedPoint encoding, no uncompressed point indicator");
        }

        int keySizeBytes = (params.getOrder().bitLength() + Byte.SIZE - 1)
                / Byte.SIZE;

        if (uncompressedPoint.length != 1 + 2 * keySizeBytes) {
            throw new IllegalArgumentException(
                    "Invalid uncompressedPoint encoding, not the correct size");
        }

        final BigInteger x = new BigInteger(1, Arrays.copyOfRange(
                uncompressedPoint, offset, offset + keySizeBytes));
        offset += keySizeBytes;
        final BigInteger y = new BigInteger(1, Arrays.copyOfRange(
                uncompressedPoint, offset, offset + keySizeBytes));
        final ECPoint w = new ECPoint(x, y);
        final ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(w, params);
        final KeyFactory keyFactory = KeyFactory.getInstance("EC");
        return (ECPublicKey) keyFactory.generatePublic(ecPublicKeySpec);
    }

    public static byte[] toUncompressedPoint(final ECPublicKey publicKey) {

        int keySizeBytes = (publicKey.getParams().getOrder().bitLength() + Byte.SIZE - 1)
                / Byte.SIZE;

        final byte[] uncompressedPoint = new byte[1 + 2 * keySizeBytes];
        int offset = 0;
        uncompressedPoint[offset++] = 0x04;

        final byte[] x = publicKey.getW().getAffineX().toByteArray();
        if (x.length <= keySizeBytes) {
            System.arraycopy(x, 0, uncompressedPoint, offset + keySizeBytes
                    - x.length, x.length);
        } else if (x.length == keySizeBytes + 1 && x[0] == 0) {
            System.arraycopy(x, 1, uncompressedPoint, offset, keySizeBytes);
        } else {
            throw new IllegalStateException("x value is too large");
        }
        offset += keySizeBytes;

        final byte[] y = publicKey.getW().getAffineY().toByteArray();
        if (y.length <= keySizeBytes) {
            System.arraycopy(y, 0, uncompressedPoint, offset + keySizeBytes
                    - y.length, y.length);
        } else if (y.length == keySizeBytes + 1 && y[0] == 0) {
            System.arraycopy(y, 1, uncompressedPoint, offset, keySizeBytes);
        } else {
            throw new IllegalStateException("y value is too large");
        }

        return uncompressedPoint;
    }

    public static void main(final String[] args) throws Exception {

        // just for testing

        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
        kpg.initialize(163);

        for (int i = 0; i < 1_000; i++) {
            final KeyPair ecKeyPair = kpg.generateKeyPair();

            final ECPublicKey ecPublicKey = (ECPublicKey) ecKeyPair.getPublic();
            final ECPublicKey retrievedEcPublicKey = fromUncompressedPoint(
                    toUncompressedPoint(ecPublicKey), ecPublicKey.getParams());
            if (!Arrays.equals(retrievedEcPublicKey.getEncoded(),
                    ecPublicKey.getEncoded())) {
                throw new IllegalArgumentException("Whoops");
            }
        }
    }
}
3wabscal

3wabscal2#

下面是我用来解包公钥的BouncyCastle方法:

public static byte[] extractData(final @NonNull PublicKey publicKey) {
    final SubjectPublicKeyInfo subjectPublicKeyInfo =
            SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    final byte[] encodedBytes = subjectPublicKeyInfo.getPublicKeyData().getBytes();
    final byte[] publicKeyData = new byte[encodedBytes.length - 1];

    System.arraycopy(encodedBytes, 1, publicKeyData, 0, encodedBytes.length - 1);

    return publicKeyData;
}
r6l8ljro

r6l8ljro3#

尝试用java生成一个未压缩的表示几乎要了我的命!真希望我能早点发现这一点(特别是Maarten Bodewes的精彩答案)。我想指出答案中的一个问题并提供一个改进:

if (x.length <= keySizeBytes) {
        System.arraycopy(x, 0, uncompressedPoint, offset + keySizeBytes
                - x.length, x.length);
    } else if (x.length == keySizeBytes + 1 && x[0] == 0) {
        System.arraycopy(x, 1, uncompressedPoint, offset, keySizeBytes);
    } else {
        throw new IllegalStateException("x value is too large");
    }

由于BigInteger输出字节数组表示的方式,这个丑陋的位是必要的:* 数组将包含表示此BigInteger所需的最小字节数,包括至少一个符号位 * 这意味着a.)如果设置了xy的最高位,a.)将0x00前置到数组,b.)将修剪前面的0x00。第一个分支处理修剪后的0x00。s,而第二个具有前置的0x00
“修剪前导零”导致代码在确定xy的预期长度时出现问题:

int keySizeBytes = (publicKey.getParams().getOrder().bitLength() + Byte.SIZE - 1)
            / Byte.SIZE;

如果曲线的order有一个前导0x00,它将被截断,并且不被bitLength考虑。结果密钥长度太短。令人难以置信的卷积(但正确的?)方式可以得到p的位长:

int keySizeBits = publicKey.getParams().getCurve().getField().getFieldSize();
int keySizeBytes = (keySizeBits + 7) >>> 3;

(The +7用于补偿不是2的幂的位长度。)
此问题至少会影响一条随标准JCA(X9_62_c2tnb431r1)提供的曲线,该曲线的顺序带有前导零:

000340340340340 34034034034034034
034034034034034 0340340340323c313
fab50589703b5ec 68d3587fec60d161c
c149c1ad4a91
iqxoj9l9

iqxoj9l94#

在BouncyCastle中,ECPoint.getEncoded(true)返回一个压缩的点表示,基本上是仿射X坐标加上一个仿射Y的符号位。

myss37ts

myss37ts5#

2021年只需使用Tink

public static byte[] pointEncode(EllipticCurves.CurveType curveType,
                                 EllipticCurves.PointFormatType format,
                                 ECPoint point)
                          throws GeneralSecurityException
3hvapo4f

3hvapo4f6#

一行BC方法是:

EC5Util.convertPoint(ecPublicKey.getParams(), ecPublicKey.getW()).getEncoded(true);

ecPublicKey是一个Java的ECPublicKey

**注:**22年用压缩点绝对没问题,爆笑专利过期,见StackExchange

相关问题