将ECC PKCS#8公钥和私钥转换为传统格式

时间:2016-06-01 08:30:36

标签: cryptography bouncycastle elliptic-curve java-security pkcs#8

我使用BouncyCastle生成ECC公共和私有:

            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

            ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable
                    .getParameterSpec("secp192r1");

            KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
            g.initialize(ecSpec, new SecureRandom());

            KeyPair pair = g.generateKeyPair();

            System.out.println(Arrays.toString(pair.getPrivate().getEncoded()));
            System.out.println(Arrays.toString(pair.getPublic().getEncoded()));


byte[] privateKey = new byte[]{48, 123, 2, 1, 0, 48, 19, 6, 7, 42, -122, 72, -50, 61, 2, 1, 6, 8, 42, -122, 72, -50, 61, 3, 1, 1, 4, 97, 48, 95, 2, 1, 1, 4, 24, 14, 117, 7, -120, 15, 109, -59, -35, 72, -91, 99, -2, 51, -120, 112, -47, -1, -115, 25, 48, -104, -93, 78, -7, -96, 10, 6, 8, 42, -122, 72, -50, 61, 3, 1, 1, -95, 52, 3, 50, 0, 4, 64, 48, -104, 32, 41, 13, 1, -75, -12, -51, -24, -13, 56, 75, 19, 74, -13, 75, -82, 35, 1, -50, -93, -115, -115, -34, -81, 119, -109, -50, -39, -57, -20, -67, 65, -50, 66, -122, 96, 84, 117, -49, -101, 54, -30, 77, -110, -122}

byte[] publicKey = new byte[]{48, 73, 48, 19, 6, 7, 42, -122, 72, -50, 61, 2, 1, 6, 8, 42, -122, 72, -50, 61, 3, 1, 1, 3, 50, 0, 4, 64, 48, -104, 32, 41, 13, 1, -75, -12, -51, -24, -13, 56, 75, 19, 74, -13, 75, -82, 35, 1, -50, -93, -115, -115, -34, -81, 119, -109, -50, -39, -57, -20, -67, 65, -50, 66, -122, 96, 84, 117, -49, -101, 54, -30, 77, -110, -122}

如何将它们转换为传统格式,以后可以在https://github.com/kmackay/micro-ecc/blob/master/uECC.h中重复使用?我需要24字节私钥和48公钥,而现在它是125和75。

1 个答案:

答案 0 :(得分:0)

给出24和48,有时在开头25或49时添加0:

    ECPrivateKey ecPrivateKey = (ECPrivateKey)privateKey;
    System.out.println(ecPrivateKey.getS().toByteArray().length);

    ECPublicKey ecPublicKey = (ECPublicKey)publicKey;
    System.out.println(ecPublicKey.getW().getAffineX().toByteArray().length + ecPublicKey.getW().getAffineY().toByteArray().length);