user129654: I've followed this tutorial on generating a Public Private key pair value and generating a valid Bitcoin address.
But one part makes me wonder if the implementation is done correctly which is the following:
ECPublicKey epub = (ECPublicKey) publicKey;
ECPoint pt = epub.getW();
byte[] pubBytes = new byte[33]; //32 + 1
pubBytes[0] = 2; //0x02
System.arraycopy(pt.getAffineX().toByteArray(), 0, pubBytes, 1, 32);

To me it seems like hardcoding the 0x02 could lead to errors when the last byte of the Y coordinate is odd or am I wrong?
If this implementation does prove to be wrong, how could I implement it correctly?

user51948: You're correct that the first byte should be 0x03 if the y-coordinate of the public key is odd. So indeed, the tutorial is not correct. If the y-coordinate is odd, just set this instead:
pubBytes[0] = 3;

It is worth noting, though, that you can simply negate the private key to achieve an even y-coordinate. This is obvious because if [s]G = Y then [-s]G = -Y. So it isn't really an issue if you did make this mistake and then wanted to fix it later. This was used in BIP-340 to make all public keys 32-bytes instead of 33, by omitting the 0x02/0x03 and always assuming the even y-coordinate.

129654: <p>I've followed <a href="https://metamug.com/article/security/java-generate-bitcoin-wallet-address.html" rel="nofollow noreferrer">this</a> tutorial on generating a Public Private key pair value and generating a valid Bitcoin address.<br>
But one part makes me wonder if the implementation is done correctly which is the following:</p>
<pre><code>ECPublicKey epub = (ECPublicKey) publicKey;
ECPoint pt = epub.getW();
byte[] pubBytes = new byte[33]; //32 + 1
pubBytes[0] = 2; //0x02
System.arraycopy(pt.getAffineX().toByteArray(), 0, pubBytes, 1, 32);
</code></pre>
<p>To me it seems like hardcoding the 0x02 could lead to errors when the last byte of the Y coordinate is odd or am I wrong?</p>
<p>If this implementation does prove to be wrong, how could I implement it correctly?</p>
 51948: <p>You're correct that the first byte should be <code>0x03</code> if the y-coordinate of the public key is odd. So indeed, the tutorial is not correct. If the y-coordinate is odd, just set this instead:</p>
<pre><code>pubBytes[0] = 3;
</code></pre>
<p>It is worth noting, though, that you can simply negate the private key to achieve an even y-coordinate. This is obvious because if <code>[s]G = Y</code> then <code>[-s]G = -Y</code>. So it isn't really an issue if you did make this mistake and then wanted to fix it later. This was used in <a href="https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki" rel="nofollow noreferrer">BIP-340</a> to make all public keys 32-bytes instead of 33, by omitting the <code>0x02</code>/<code>0x03</code> and always assuming the even y-coordinate.</p>
