Generating a ECDSA Private key in bouncy castle returns a PUBLIC key

时光总嘲笑我的痴心妄想 提交于 2019-12-06 03:04:07

Java outputs key in the encoded format. You should try:

private String getPrivateKeyAsHex(PrivateKey privateKey) {

    ECPrivateKey ecPrivateKey = (ECPrivateKey) privateKey;
    byte[] privateKeyBytes = new byte[PRIVATE_KEY_LENGTH];
    writeToStream(privateKeyBytes, 0, ecPrivateKey.getS(), PRIVATE_KEY_LENGTH);

    String hex = Hex.toHexString(privateKeyBytes);

    logger.debug("Private key bytes: " + Arrays.toString(privateKeyBytes));
    logger.debug("Private key hex: " + hex);

    return hex;
}

private String getPublicKeyAsHex(PublicKey publicKey) {

    ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
    ECPoint ecPoint = ecPublicKey.getW();

    byte[] publicKeyBytes = new byte[PUBLIC_KEY_LENGTH];
    writeToStream(publicKeyBytes, 0, ecPoint.getAffineX(), PRIVATE_KEY_LENGTH);
    writeToStream(publicKeyBytes, PRIVATE_KEY_LENGTH, ecPoint.getAffineY(), PRIVATE_KEY_LENGTH);

    String hex = Hex.toHexString(publicKeyBytes);

    logger.debug("Public key bytes: " + Arrays.toString(publicKeyBytes));
    logger.debug("Public key hex: " + hex);

    return hex;
}

private void writeToStream(byte[] stream, int start, BigInteger value, int size) {
    byte[] data = value.toByteArray();
    int length = Math.min(size, data.length);
    int writeStart = start + size - length;
    int readStart = data.length - length;
    System.arraycopy(data, readStart, stream, writeStart, length);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!