@@ -907,15 +907,31 @@ static byte[] encode(final ECPublicKey pubKey) {
907
907
}
908
908
909
909
private static byte [] encode (final int bitLength , final ECPoint point ) {
910
- int keyLengthBytes = bitLength / 8 ;
911
- byte [] encoded = new byte [1 + 2 * keyLengthBytes ];
910
+ if ( point == ECPoint .POINT_INFINITY ) return new byte [1 ];
911
+
912
+ final int bytesLength = (bitLength + 7 ) / 8 ;
913
+ byte [] encoded = new byte [1 + bytesLength + bytesLength ];
912
914
913
915
encoded [0 ] = 0x04 ;
914
916
915
- System . arraycopy (point .getAffineX (). toByteArray (), 0 , encoded , 1 , keyLengthBytes );
916
- System . arraycopy (point .getAffineY (). toByteArray (), 0 , encoded , 1 + keyLengthBytes , keyLengthBytes );
917
+ addIntBytes (point .getAffineX (), bytesLength , encoded , 1 );
918
+ addIntBytes (point .getAffineY (), bytesLength , encoded , 1 + bytesLength );
917
919
918
920
return encoded ;
919
921
}
920
922
923
+ private static void addIntBytes (BigInteger i , final int length , final byte [] dest , final int destOffset ) {
924
+ final byte [] bytes = i .toByteArray ();
925
+
926
+ if (length < bytes .length ) {
927
+ System .arraycopy (bytes , bytes .length - length , dest , destOffset , length );
928
+ }
929
+ else if (length > bytes .length ) {
930
+ System .arraycopy (bytes , 0 , dest , destOffset + (length - bytes .length ), bytes .length );
931
+ }
932
+ else {
933
+ System .arraycopy (bytes , 0 , dest , destOffset , length );
934
+ }
935
+ }
936
+
921
937
}
0 commit comments