Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate PublicKey for PrivateKey in X25519?

I'm working with X25519-keys based encryption at the moment.

My question is, basically, how to derive PublicKey from existing X25519 PrivateKey?

I have found the code in the XDHKeyPairGenerator:

BigInteger publicKey = ops.computePublic(privateKey.clone());

But this package is platform-specific, thus not accessible. And I can't find a method to do it through publicly-accessible interfaces.

like image 263
Dmytro Titov Avatar asked Jan 18 '26 02:01

Dmytro Titov


1 Answers

So far I've discovered only one way to do it through JDK-provided interfaces (without using any additional libraries like Bouncy Castle or Google Tink):

public class StaticSecureRandom extends SecureRandom {

    private final byte[] privateKey;

    public StaticSecureRandom(byte[] privateKey) {
        this.privateKey = privateKey.clone();
    }

    @Override
    public void nextBytes(byte[] bytes) {
        System.arraycopy(privateKey, 0, bytes, 0, privateKey.length);
    }

}
    public PublicKey generatePublicKeyFromPrivate(PrivateKey privateKey) throws GeneralSecurityException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(X25519);
        keyPairGenerator.initialize(new NamedParameterSpec(X25519), new StaticSecureRandom(getScalar(privateKey)));
        return keyPairGenerator.generateKeyPair().getPublic();
    }

It's not a very elegant solution, but it works without any third-party libraries and I couldn't find any other way.

like image 125
Dmytro Titov Avatar answered Jan 20 '26 17:01

Dmytro Titov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!