I'm doing a spin-off request from this: EC Key request
As my problem is a bit different but similar.
I have the following private key (in this format, not a file):
MHcCAQEEID0VR/I814rQUqWIYPEhno+3kexN/jN2n1ub+mJ6ZWyhoAoGCCqGSM49AwEHoUQDQgAEwKMBv29ByaSLiGF0FctuyB+Hs2oZ1kDIYhTVllPexNGudAlm8IWOH0e+Exc97/zBdawu7Yl+XytQONszGzAK7w==
And I want to load it to an ECPrivateKey (possibly to have an ECPublicKey too). Following a bunch of links and ideas, i got two possible code hints: 1- Bouncy castle:
val privateKey = "PRIVATE KEY ABOVE, MHc..."
val rdr = StringReader(privateKey)
val parsed = PEMParser(rdr).readObject()
val pair = JcaPEMKeyConverter().getKeyPair(parsed as PEMKeyPair)
println("[load_ec_pair_keys] Algorithm: ${pair.private.algorithm} , Private Key: ${pair.private} , Public Key: ${pair.public}")
return pair
The output gives:
Algorithm: ECDSA , Private Key: EC Private Key >[fe:60:f6:24:f9:ba:61:4f:60:98:d9:72:b2:14:87:c8:13:c2:3f:f4]
X: c0a301bf6f41c9a48b88617415cb6ec81f87b36a19d640c86214d59653dec4d1
Y: ae740966f0858e1f47be13173deffcc175ac2eed897e5f2b5038db331b300aef
But if I save that private key to a pem file and use openssl: openssl ec -noout -text -inform PEM -in private.pem The result is:
read EC key Private-Key: (256 bit)
priv: 3d:15:47:f2:3c:d7:8a:d0:52:a5:88:60:f1:21:9e: 8f:b7:91:ec:4d:fe:33:76:9f:5b:9b:fa:62:7a:65: 6c:a1
pub: 04:c0:a3:01:bf:6f:41:c9:a4:8b:88:61:74:15:cb: 6e:c8:1f:87:b3:6a:19:d6:40:c8:62:14:d5:96:53: de:c4:d1:ae:74:09:66:f0:85:8e:1f:47:be:13:17: 3d:ef:fc:c1:75:ac:2e:ed:89:7e:5f:2b:50:38:db: 33:1b:30:0a:ef
ASN1 OID: prime256v1
NIST CURVE: P-256
So those seems different to me, and using the help (see comments too) of @dave_thompson_085 I ended up with the following code: 2 - No BouncyCastle, java.security package:
fun load_ec_full(): ECPrivateKey {
val a = AlgorithmParameters.getInstance("EC")
a.init(ECGenParameterSpec("secp256r1"))
val p: ECParameterSpec = a.getParameterSpec(ECParameterSpec::class.java)
println("p=(dec)" + (p.curve.field as ECFieldFp).p)
val G: ECPoint = p.generator
System.out.format("Gx=(hex)%032x%n", G.affineX)
System.out.format("Gy=(hex)%032x%n", G.affineY)
// val headerPrefix = Hex.decode("303E020100301006072A8648CE3D020106052B8104000A042730250201010420") //secp256k1
val headerPrefix = Hex.decode("308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b02") //secp256r1
val privateKSimple =
"MHcCAQEEID0VR/I814rQUqWIYPEhno+3kexN/jN2n1ub+mJ6ZWyhoAoGCCqGSM49AwEHoUQDQgAEwKMBv29ByaSLiGF0FctuyB+Hs2oZ1kDIYhTVllPexNGudAlm8IWO" +
"H0e+Exc97/zBdawu7Yl+XytQONszGzAK7w=="
val decodedPK = java.util.Base64.getDecoder().decode(privateKSimple)
val kf: KeyFactory = KeyFactory.getInstance("EC")
val k1 = kf.generatePrivate(PKCS8EncodedKeySpec(headerPrefix + decodedPK)) as ECPrivateKey
val p2 = k1.params
println("again p=(dec)" + (p2.curve.field as ECFieldFp).p)
println("KEY: $k1")
If i use the first headerPrefix (secp256k1) i got a key with output:
p=(dec)115792089210356248762697446949407573530086143415290314195533631308867097853951
Gx=(hex)6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296
Gy=(hex)4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5
again p=(dec)115792089237316195423570985008687907853269984665640564039457584007908834671663
KEY: sun.security.ec.ECPrivateKeyImpl@b8485def
So the key is not written out, but is different for the one generated above).
If I use the headerPrefix generated using the openssl command hinted in the other response: openssl pkcs8 -topk8 -nocrypt -in private.pem -out pkcs8der -outform der that i obtained as: "308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b02" this breaks the code:
java.security.InvalidKeyException: Invalid EC private key java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Invalid EC private key at jdk.crypto.ec/sun.security.ec.ECKeyFactory.engineGeneratePrivate(Unknown Source) at java.base/java.security.KeyFactory.generatePrivate(Unknown Source) at com.mhamdaoui.smartcardreader.ExampleUnitTest.load_ec_full(ExampleUnitTest.kt:249) at com.mhamdaoui.smartcardreader.ExampleUnitTest.test load rsa key(ExampleUnitTest.kt:273) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.base/java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:55) at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63) at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329) at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293) at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) at org.junit.runners.ParentRunner.run(ParentRunner.java:413) at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:100) at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:107) at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:41) at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:108) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:40) at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:60) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:52) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.base/java.lang.reflect.Method.invoke(Unknown Source) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33) at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94) at jdk.proxy1/jdk.proxy1.$Proxy2.processTestClass(Unknown Source) at org.gradle.api.internal.tasks.testing.worker.TestWorker$2.run(TestWorker.java:176) at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129) at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100) at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60) at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56) at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:113) at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:65) at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69) at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74) Caused by: java.security.InvalidKeyException: Invalid EC private key at jdk.crypto.ec/sun.security.ec.ECPrivateKeyImpl.parseKeyBits(Unknown Source) at jdk.crypto.ec/sun.security.ec.ECPrivateKeyImpl.(Unknown Source) at jdk.crypto.ec/sun.security.ec.ECKeyFactory.implGeneratePrivate(Unknown Source) ... 52 more Caused by: java.io.IOException: Integer exceeds maximum valid value at java.base/sun.security.util.DerValue.getIntegerInternal(Unknown Source) at java.base/sun.security.util.DerValue.getInteger(Unknown Source) at java.base/sun.security.util.DerInputStream.getInteger(Unknown Source) ... 55 more
I'm quite lost now as I'm new on the field, and honestly this is only a small side of my project. The only thing I know is that in oder to be sure the key is parsed correctly, the following code on the key should give the result: "c0b77375"
val xCoord = privateKey.params.generator.affineX
val calculateSha256 = VASUtils.calculateSha256(xCoord.toByteArray())
val result = calculateSha256.copyOfRange(0, 4)
To give you a bit more context, I'm trying to replicate on Android (Kotlin, but is JVM...) the AppleVAS reading code that can be found here: https://github.com/RfidResearchGroup/proxmark3/blob/32f892e512d97be402c0abaf6f00675686ed0893/client/src/cmdhfvas.c#L280
I have the correct cryptogram data and other variables, but method GetPrivateKeyHint in Java fails for me and the given key.
If someone can help me, or can check what I'm doing wrong it would be very helpful, I'm planning to put all my work on a github open repository at the end, so it's not a commercial action.