Reading elliptic curve private key from file with BouncyCastle

前端 未结 3 1170
陌清茗
陌清茗 2020-11-30 12:07

The BouncyCastle cryptography APIs allow for creating and verifying digital signatures using the regular java.security package objects, such as java.secur

3条回答
  •  抹茶落季
    2020-11-30 12:37

    Since I only need this for a quick and dirty demo, I solved it in the following way (in Scala). First, I generate a public private key pair in the REPL and print out its data:

    Security.addProvider(new BouncyCastleProvider)
    
    val SignatureScheme = "some signature scheme, eg ECDSA"
    val RandomAlgorithm = "some random algorithm, eg SHA1PRNG"
    
    val keygen = KeyPairGenerator.getInstance(SignatureScheme)
    val rng = SecureRandom.getInstance(RandomAlgorithm)
    rng.setSeed(seed)
    keygen.initialize(KeySize, rng)
    
    val kp = keygen.generateKeyPair()
    println(kp.getPublic.getEncoded.toSeq) // toSeq so that Scala actually prints it
    println(kp.getPrivate.getEncoded.toSeq)
    

    Then using the generated data,

    val hardcodedPublic = Array[Byte]( /* data */ )
    val hardcodedPrivate = Array[Byte]( /* data */ )
    
    val factory = KeyFactory.getInstance(SignatureScheme)
    
    val publicSpec = new X509EncodedKeySpec(hardcodedPublic)
    val publicKey = factory.generatePublic(publicSpec)
    
    val privateSpec = new PKCS8EncodedKeySpec(hardcodedPrivate)
    val privateKey = factory.generatePrivate(privateSpec)
    

    The key thing you need to know here is that by default public key data uses X509 encoding and private key data uses PKCS8 encoding. It should be possible to get OpenSSL to output these formats and parse them manually, but I did not check how.

    I used information from this blog post about SpongyCastle (which is Android's BouncyCastle alias) quite helpful. It is unfortunate that documentation is fragmented like this, and that BouncyCastle's wiki was down at the time of this question.

    Update: the BouncyCastle wiki is up, and you can find the documentation here.

提交回复
热议问题