简体   繁体   中英

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.

You must scalar multiply the private key (which is just a big number) by the 25519 curve generator point .

Here is some code in python to illustrate:

from tinyec import registry
import secrets

curve = registry.get_curve('curve25519')

def compress_point(point):
    return hex(point.x) + hex(point.y % 2)[2:]


privKey = secrets.randbelow(curve.field.n)
pubKey = privKey * curve.g //the key step for you...


print("private key:", hex(privKey))
print("public key:", compress_point(pubKey))

If you let me know the Java lib I will try and help further.

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.

BouncyCastle has Ed25519KeyPairGenerator, X25519KeyPairGenerator, PrivateKeyInfoFactory, and SubjectPublicKeyInfoFactory that can assist with making the keys. Here's an example in C#. Substitute ECKeyPairGenerator with X25519KeyPairGenerator. This example uses a standard keys and a NIST curve since I couldn't get Curve25519 working with the X25519 generated keys because the oid isn't supported in the current implementation.

public static async Task Bouncy()
    {
        var originalSecret = "X25519 example";
        var message = Encoding.UTF8.GetBytes(originalSecret);

        // Generate signing keys
        var gen = new Ed25519KeyPairGenerator();
        gen.Init(new Ed25519KeyGenerationParameters(new SecureRandom()));
        var kp = gen.GenerateKeyPair();

        // Sign data with private key
        var signer = new Ed25519Signer();
        signer.Init(true, kp.Private);
        signer.BlockUpdate(message, 0, message.Length);
        var sig = signer.GenerateSignature();

        // Verify signature with public key
        var verifier = new Ed25519Signer();
        verifier.Init(false, kp.Public);
        verifier.BlockUpdate(message, 0, message.Length);
        var sigresult = verifier.VerifySignature(sig);

        // Generate encryption keys
        var genX = new ECKeyPairGenerator();
        genX.Init(new KeyGenerationParameters(new SecureRandom(), 521));

        var p1 = genX.GenerateKeyPair();
        var p1_private = ECPrivateKeyStructure.GetInstance(PrivateKeyInfoFactory.CreatePrivateKeyInfo(p1.Private));
        var p1_x25519_priv = new X25519PrivateKeyParameters(p1_private.GetDerEncoded(), 0);

        var p2 = genX.GenerateKeyPair();
        var p2_public = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(p2.Public);
        var p2_x25519_pub = new X25519PublicKeyParameters(p2_public.GetDerEncoded(), 0);

        // Generate secret from keys
        var secret = new byte[32];
        p1_x25519_priv.GenerateSecret(p2_x25519_pub, secret, 0);

        // Setup ECIES (Elliptical Curve Integrated Encryption Scheme)
        var gcm = new GcmBlockCipher(new AesEngine());
        var ies = new IesEngine(new ECDHBasicAgreement(), new Kdf2BytesGenerator(new Sha512Digest()),
            new HMac(new Sha512Digest()), new PaddedBufferedBlockCipher(gcm.GetUnderlyingCipher()));

        // 256bit MAC, 256 key
        var p = new IesWithCipherParameters(secret, new byte[1], 256, 256);

        // Encrypt secret
        ies.Init(true, p1.Private, p2.Public, p);
        var encrypted = ies.ProcessBlock(message, 0, message.Length);

        // Decrypt secret
        ies.Init(false, p2.Private, p1.Public, p);
        var decrypted = ies.ProcessBlock(encrypted, 0, encrypted.Length);
        var decrypted_string = Encoding.UTF8.GetString(decrypted);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM