How can I generate a valid ECDSA EC key pair?

前端 未结 2 1743
面向向阳花
面向向阳花 2021-01-14 18:28

I am trying to generate ECDSA key pair using SpongyCastle in Android. This is the code:

static {
    Security.insertProviderAt(new org.spongycastle.jce.provi         


        
2条回答
  •  执念已碎
    2021-01-14 18:52

    More practical example. Convert generated public key to decoded bytes array or hex string:

    public 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);
    }
    

    Convert decoded bytes array back to PublicKey:

    KeyFactory factory = KeyFactory.getInstance(ALGORITHM, ALGORITHM_PROVIDER);
    
    ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(CURVE);
    
    ECNamedCurveSpec params = new ECNamedCurveSpec(CURVE, spec.getCurve(), spec.getG(), spec.getN());
    
    BigInteger xCoordinate = new BigInteger(1, Arrays.copyOfRange(decodedPublicKey, 0, PRIVATE_KEY_LENGTH));
    BigInteger yCoordinate = new BigInteger(1, Arrays.copyOfRange(decodedPublicKey, PRIVATE_KEY_LENGTH, PUBLIC_KEY_LENGTH));
    java.security.spec.ECPoint w = new java.security.spec.ECPoint(xCoordinate, yCoordinate);
    
    PublicKey encodedPublicKey = factory.generatePublic(new java.security.spec.ECPublicKeySpec(w, params));
    

提交回复
热议问题