github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/crypto/secp256k1/libsecp256k1/src/java/org/bitcoin/NativeSecp256k1.java (about) 1 package org.bitcoin; 2 3 import java.nio.ByteBuffer; 4 import java.nio.ByteOrder; 5 6 import com.google.common.base.Preconditions; 7 8 9 /** 10 * This class holds native methods to handle ECDSA verification. 11 * You can find an example library that can be used for this at 12 * https://github.com/sipa/secp256k1 13 */ 14 public class NativeSecp256k1 { 15 public static final boolean enabled; 16 static { 17 boolean isEnabled = true; 18 try { 19 System.loadLibrary("javasecp256k1"); 20 } catch (UnsatisfiedLinkError e) { 21 isEnabled = false; 22 } 23 enabled = isEnabled; 24 } 25 26 private static ThreadLocal<ByteBuffer> nativeECDSABuffer = new ThreadLocal<ByteBuffer>(); 27 /** 28 * Verifies the given secp256k1 signature in native code. 29 * Calling when enabled == false is undefined (probably library not loaded) 30 * 31 * @param data The data which was signed, must be exactly 32 bytes 32 * @param signature The signature 33 * @param pub The public key which did the signing 34 */ 35 public static boolean verify(byte[] data, byte[] signature, byte[] pub) { 36 Preconditions.checkArgument(data.length == 32 && signature.length <= 520 && pub.length <= 520); 37 38 ByteBuffer byteBuff = nativeECDSABuffer.get(); 39 if (byteBuff == null) { 40 byteBuff = ByteBuffer.allocateDirect(32 + 8 + 520 + 520); 41 byteBuff.order(ByteOrder.nativeOrder()); 42 nativeECDSABuffer.set(byteBuff); 43 } 44 byteBuff.rewind(); 45 byteBuff.put(data); 46 byteBuff.putInt(signature.length); 47 byteBuff.putInt(pub.length); 48 byteBuff.put(signature); 49 byteBuff.put(pub); 50 return secp256k1_ecdsa_verify(byteBuff) == 1; 51 } 52 53 /** 54 * @param byteBuff signature format is byte[32] data, 55 * native-endian int signatureLength, native-endian int pubkeyLength, 56 * byte[signatureLength] signature, byte[pubkeyLength] pub 57 * @returns 1 for valid signature, anything else for invalid 58 */ 59 private static native int secp256k1_ecdsa_verify(ByteBuffer byteBuff); 60 }