EDIT: Got my confusion sorted out, thanks to
ETFbitcoin
I'm getting a correct private key, but an incorrect public key, with the following java program:
import com.google.bitcoin.core.Base58;
import java.io.UnsupportedEncodingException;
import java.security.........
////////////////////////////////////////////////////////////////////////////////////
public static String to64(String s) {
switch(s.length()) {
case 62: return "00" + s;
case 63: return "0" + s;
case 64: return s;
default:
throw new IllegalArgumentException("Invalid key: " + s);
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, UnsupportedEncodingException, NoSuchProviderException {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec secp = new ECGenParameterSpec("secp256k1");
keyGen.initialize(secp);
KeyPair kp = keyGen.generateKeyPair();
PublicKey pub = kp.getPublic();
PrivateKey pvt = kp.getPrivate();
ECPrivateKey epvt = (ECPrivateKey)pvt;
String sepvt = to64(epvt.getS().toString(16)).toUpperCase();
ECPublicKey epub = (ECPublicKey)pub;
ECPoint pt = epub.getW();
String sx = to64(pt.getAffineX().toString(16)).toUpperCase();
String sy = to64(pt.getAffineY().toString(16)).toUpperCase();
String bcPub = "04" + sx + sy;
MessageDigest sha = MessageDigest.getInstance("SHA-256");
byte[] s1 = sha.digest(bcPub.getBytes("UTF-8"));
MessageDigest rmd = MessageDigest.getInstance("RipeMD160", "BC");
byte[] r1 = rmd.digest(s1);
byte[] r2 = new byte[r1.length + 1];
r2[0] = 0;
System.arraycopy(r1, 0, r2, 1, r1.length);
byte[] s2 = sha.digest(r2);
byte[] s3 = sha.digest(s2);
byte[] a1 = new byte[25];
System.arraycopy(r2, 0, a1, 0, r2.length);
System.arraycopy(s3, 0, a1, 20, 5);
System.out.println("Public Key: " + Base58.encode(a1));
System.out.println("Private Key: " + sepvt);}}
For example, instead of:
I should get:
Public key: 1BuXQcCU7eQA6z5N5qqNUubjQLk3vrATVk
Private key: 93B16A46CF1D71E79CA28BFFA8499B6F7412BEB1514CC6FE271AED19F3FAF946
Any idea what I'm doing wrong here?