As indicated, the private key is in X9.62 format. It cannot be in PKCS#1 format because that format specifies RSA, not ECC.
Furthermore, your PKCS#8 private key contains more information than the X9.62 formatted private key that you've extracted from it. You can see the decoding of PKCS#8 here:
SEQUENCE (3 elem)
INTEGER 0
SEQUENCE (2 elem)
OBJECT IDENTIFIER 1.2.840.10045.2.1 ecPublicKey (ANSI X9.62 public key type)
OBJECT IDENTIFIER 1.3.132.0.10 secp256k1 (SECG (Certicom) named elliptic curve)
OCTET STRING (1 elem)
SEQUENCE (4 elem)
INTEGER 1
OCTET STRING (32 byte) 9CDDA50E9E839066257291DBCBDBD9A8A177F350AA522A128163AB7E955622C5
[0] (1 elem)
OBJECT IDENTIFIER 1.3.132.0.10 secp256k1 (SECG (Certicom) named elliptic curve)
[1] (1 elem)
BIT STRING (520 bit) ... the optional public key ...
The internal X9.62 key is the sequence within the octet string and the secret (S) is the 32 byte octet string.
So you have to add back the information. This is an AlgorithmIdentifier
that indicates ecPublicKey
operations as well as the curve used (repeated for the public key).
So without further ado, the operations to recreate the PKCS#8 structure (with x962
replacing pkcs1
):
ASN1Primitive prim = ASN1Primitive.fromByteArray(x962);
PrivateKeyInfo keyInfo = new PrivateKeyInfo(new AlgorithmIdentifier(
X9ObjectIdentifiers.id_ecPublicKey,
SECObjectIdentifiers.secp256k1), prim);
note that this is the non-encrypted variant of PKCS#8 which just shows the private key type. The encrypted variant encrypts this structure and adds information on the used wrapping mechanism (e.g. AES encrypted).