ensure consistent keypair implementation is used for all constructors

This commit is contained in:
Craig Raw 2025-01-22 11:33:45 +02:00
parent 89a6b1296e
commit 0df1f79e5c

View file

@ -1,6 +1,5 @@
package com.sparrowwallet.drongo.crypto; package com.sparrowwallet.drongo.crypto;
import com.sparrowwallet.drongo.Utils;
import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
@ -16,21 +15,20 @@ import java.security.spec.AlgorithmParameterSpec;
import java.util.Optional; import java.util.Optional;
public class X25519Key { public class X25519Key {
private KeyPair keyPair; private final KeyPair keyPair;
private final AlgorithmParameterSpec ecSpec; private final AlgorithmParameterSpec ecSpec;
public X25519Key() { public X25519Key() {
this(generatePrivateKey());
}
public X25519Key(byte[] priv) {
try { try {
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("X25519"); final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("X25519");
this.keyPair = keyPairGenerator.generateKeyPair();
this.ecSpec = keyPairGenerator.generateKeyPair().getPrivate().getParams(); this.ecSpec = keyPairGenerator.generateKeyPair().getPrivate().getParams();
} catch(NoSuchAlgorithmException e) { } catch(NoSuchAlgorithmException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
}
public X25519Key(byte[] priv) {
this();
X25519PrivateKeyParameters privateKeyParams = new X25519PrivateKeyParameters(priv, 0); X25519PrivateKeyParameters privateKeyParams = new X25519PrivateKeyParameters(priv, 0);
X25519PublicKeyParameters publicKeyParams = privateKeyParams.generatePublicKey(); X25519PublicKeyParameters publicKeyParams = privateKeyParams.generatePublicKey();
@ -45,11 +43,14 @@ public class X25519Key {
} }
public byte[] getRawPrivateKeyBytes() { public byte[] getRawPrivateKeyBytes() {
return Utils.getRawKeyBytesFromPKCS8(keyPair.getPrivate()); return keyPair.getPrivate().getEncoded();
} }
public byte[] getRawPublicKeyBytes() { private static byte[] generatePrivateKey() {
return Utils.getRawKeyBytesFromX509(keyPair.getPublic()); SecureRandom secureRandom = new SecureRandom();
byte[] privateKey = new byte[32];
secureRandom.nextBytes(privateKey);
return privateKey;
} }
public class BouncyCastlePrivateKey implements XECPrivateKey { public class BouncyCastlePrivateKey implements XECPrivateKey {