Java Code Examples for org.spongycastle.crypto.signers.ECDSASigner#init()

The following examples show how to use org.spongycastle.crypto.signers.ECDSASigner#init() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ECKey.java    From asf-sdk with GNU General Public License v3.0 6 votes vote down vote up
/**
 * <p>Verifies the given ECDSA signature against the message bytes using the public key bytes.</p>
 *
 * <p>When using native ECDSA verification, data must be 32 bytes, and no element may be
 * larger than 520 bytes.</p>
 *
 * @param data Hash of the data to verify.
 * @param signature signature.
 * @param pub The public key bytes to use.
 *
 * @return -
 */
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) {
  ECDSASigner signer = new ECDSASigner();
  ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE.getCurve()
      .decodePoint(pub), CURVE);
  signer.init(false, params);
  try {
    return signer.verifySignature(data, signature.r, signature.s);
  } catch (NullPointerException npe) {
    // Bouncy Castle contains a bug that can cause NPEs given specially crafted signatures.
    // Those signatures are inherently invalid/attack sigs so we just fail them here rather
    // than crash the thread.
    //            logger.error("Caught NPE inside bouncy castle", npe);
    return false;
  }
}
 
Example 2
Source File: ECKey.java    From tron-wallet-android with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Verifies the given ECDSA signature against the message bytes using the public key bytes.</p>
 * <p> <p>When using native ECDSA verification, data must be 32 bytes, and no element may be
 * larger than 520 bytes.</p>
 *
 * @param data Hash of the data to verify.
 * @param signature signature.
 * @param pub The public key bytes to use.
 * @return -
 */
public static boolean verify(byte[] data, ECDSASignature signature,
    byte[] pub) {
  ECDSASigner signer = new ECDSASigner();
  ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE
      .getCurve().decodePoint(pub), CURVE);
  signer.init(false, params);
  try {
    return signer.verifySignature(data, signature.r, signature.s);
  } catch (NullPointerException npe) {
    // Bouncy Castle contains a bug that can cause NPEs given
    // specially crafted signatures.
    // Those signatures are inherently invalid/attack sigs so we just
    // fail them here rather than crash the thread.
    logger.error("Caught NPE inside bouncy castle", npe);
    return false;
  }
}
 
Example 3
Source File: ECKey.java    From wkcwallet-java with Apache License 2.0 6 votes vote down vote up
/**
 * Signs the given hash and returns the R and S components as BigIntegers
 * and put them in ECDSASignature
 *
 * @param input
 *            to sign
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
    if (input.length != 32) {
        throw new IllegalArgumentException("Expected 32 byte input to ECDSA signature, not " + input.length);
    }
    // No decryption of private key required.
    if (privKey == null)
        throw new MissingPrivateKeyException();
    if (privKey instanceof BCECPrivateKey) {
        ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(((BCECPrivateKey) privKey).getD(), CURVE);
        signer.init(true, privKeyParams);
        BigInteger[] components = signer.generateSignature(input);
        return new ECDSASignature(components[0], components[1]).toCanonicalised();
    } else {
        try {
            final Signature ecSig = ECSignatureFactory.getRawInstance(provider);
            ecSig.initSign(privKey);
            ecSig.update(input);
            final byte[] derSignature = ecSig.sign();
            return ECDSASignature.decodeFromDER(derSignature).toCanonicalised();
        } catch (SignatureException | InvalidKeyException ex) {
            throw new RuntimeException("ECKey signing error", ex);
        }
    }
}
 
Example 4
Source File: ECKey.java    From bitherj with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Verifies the given ECDSA signature against the message bytes using the public key bytes.</p>
 * <p/>
 * <p>When using native ECDSA verification, data must be 32 bytes, and no element may be
 * larger than 520 bytes.</p>
 *
 * @param data      Hash of the data to verify.
 * @param signature ASN.1 encoded signature.
 * @param pub       The public key bytes to use.
 */
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) {
    if (FAKE_SIGNATURES)
        return true;

    if (NativeSecp256k1.enabled)
        return NativeSecp256k1.verify(data, signature.encodeToDER(), pub);

    ECDSASigner signer = new ECDSASigner();
    ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pub), CURVE);
    signer.init(false, params);
    try {
        return signer.verifySignature(data, signature.r, signature.s);
    } catch (NullPointerException e) {
        // Bouncy Castle contains a bug that can cause NPEs given specially crafted signatures. Those signatures
        // are inherently invalid/attack sigs so we just fail them here rather than crash the thread.
        log.error("Caught NPE inside bouncy castle");
        e.printStackTrace();
        return false;
    }
}
 
Example 5
Source File: ECKey.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
protected ECDSASignature doSign(Sha256Hash input, BigInteger privateKeyForSigning) {
    if (Secp256k1Context.isEnabled()) {
        try {
            byte[] signature = NativeSecp256k1.sign(
                    input.getBytes(),
                    Utils.bigIntegerToBytes(privateKeyForSigning, 32)
            );
            return ECDSASignature.decodeFromDER(signature);
        } catch (NativeSecp256k1Util.AssertFailException e) {
            log.error("Caught AssertFailException inside secp256k1", e);
            throw new RuntimeException(e);
        }
    }
    if (FAKE_SIGNATURES)
        return TransactionSignature.dummy();
    checkNotNull(privateKeyForSigning);
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE);
    signer.init(true, privKey);
    BigInteger[] components = signer.generateSignature(input.getBytes());
    return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
 
Example 6
Source File: ECKey.java    From tron-wallet-android with Apache License 2.0 5 votes vote down vote up
/**
 * Signs the given hash and returns the R and S components as BigIntegers and putData them in
 * ECDSASignature
 *
 * @param input to sign
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
  if (input.length != 32) {
    throw new IllegalArgumentException("Expected 32 byte input to " +
        "ECDSA signature, not " + input.length);
  }
  // No decryption of private key required.
  if (privKey == null) {
    throw new MissingPrivateKeyException();
  }
  if (privKey instanceof BCECPrivateKey) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new
        SHA256Digest()));
    ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters
        (((BCECPrivateKey) privKey).getD(), CURVE);
    signer.init(true, privKeyParams);
    BigInteger[] components = signer.generateSignature(input);
    return new ECDSASignature(components[0], components[1])
        .toCanonicalised();
  } else {
    try {
      final Signature ecSig = ECSignatureFactory.getRawInstance
          (provider);
      ecSig.initSign(privKey);
      ecSig.update(input);
      final byte[] derSignature = ecSig.sign();
      return ECDSASignature.decodeFromDER(derSignature)
          .toCanonicalised();
    } catch (SignatureException | InvalidKeyException ex) {
      throw new RuntimeException("ECKey signing error", ex);
    }
  }
}
 
Example 7
Source File: NamedCurve.java    From UAF with Apache License 2.0 5 votes vote down vote up
public static boolean verify(byte[] pub, byte[] dataForSigning,
		BigInteger[] rs) {
	ECDSASigner signer = new ECDSASigner();
	X9ECParameters params = SECNamedCurves.getByName("secp256r1");
	ECDomainParameters ecParams = new ECDomainParameters(params.getCurve(),
			params.getG(), params.getN(), params.getH());
	ECPublicKeyParameters pubKeyParams = new ECPublicKeyParameters(ecParams
			.getCurve().decodePoint(pub), ecParams);
	signer.init(false, pubKeyParams);

	return signer.verifySignature(dataForSigning, rs[0].abs(), rs[1].abs());
}
 
Example 8
Source File: BitCoinECKeyPair.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 5 votes vote down vote up
public byte[] signBTC(byte[] hash) {
    ECDSASigner signer = new ECDSASigner();
    signer.init(true, new ECPrivateKeyParameters(priv, domain));
    BigInteger[] signature = signer.generateSignature(hash);
    ByteArrayOutputStream s = new ByteArrayOutputStream();
    try {
        DERSequenceGenerator seq = new DERSequenceGenerator(s);
        seq.addObject(new DERInteger(signature[0]));
        seq.addObject(new DERInteger(signature[1]));
        seq.close();
        return s.toByteArray();
    } catch (IOException e) {
    }
    return null;
}
 
Example 9
Source File: ECKey.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 * <p>Verifies the given ECDSA signature against the message bytes using the public key bytes.</p>
 * 
 * <p>When using native ECDSA verification, data must be 32 bytes, and no element may be
 * larger than 520 bytes.</p>
 *
 * @param data      Hash of the data to verify.
 * @param signature signature.
 * @param pub       The public key bytes to use.
 */
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) {
    ECDSASigner signer = new ECDSASigner();
    ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pub), CURVE);
    signer.init(false, params);
    try {
        return signer.verifySignature(data, signature.r, signature.s);
    } catch (NullPointerException npe) {
        // Bouncy Castle contains a bug that can cause NPEs given specially crafted signatures. 
    	// Those signatures are inherently invalid/attack sigs so we just fail them here rather than crash the thread.
        logger.error("Caught NPE inside bouncy castle", npe);
        return false;
    }
}
 
Example 10
Source File: ECKey.java    From asf-sdk with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Signs the given hash and returns the R and S components as BigIntegers
 * and put them in ECDSASignature
 *
 * @param input to sign
 *
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
  if (input.length != 32) {
    throw new IllegalArgumentException(
        "Expected 32 byte input to ECDSA signature, not " + input.length);
  }
  // No decryption of private key required.
  if (privKey == null) throw new MissingPrivateKeyException();
  if (privKey instanceof BCECPrivateKey) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    ECPrivateKeyParameters privKeyParams =
        new ECPrivateKeyParameters(((BCECPrivateKey) privKey).getD(), CURVE);
    signer.init(true, privKeyParams);
    BigInteger[] components = signer.generateSignature(input);
    return new ECDSASignature(components[0], components[1]).toCanonicalised();
  } else {
    try {
      Signature ecSig = ECSignatureFactory.getRawInstance(provider);
      ecSig.initSign(privKey);
      ecSig.update(input);
      byte[] derSignature = ecSig.sign();
      return ECDSASignature.decodeFromDER(derSignature)
          .toCanonicalised();
    } catch (SignatureException | InvalidKeyException ex) {
      throw new RuntimeException("ECKey signing error", ex);
    }
  }
}
 
Example 11
Source File: Secp256k1.java    From neb.java with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static byte[] Sign(byte[] data, byte[] privateKey) {
    if (data.length != 32) {
        throw new IllegalArgumentException("Expected 32 byte input to ECDSA signature, not " + data.length);
    }
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(new BigInteger(1, privateKey), CURVE);
    signer.init(true, privKey);
    BigInteger[] components = signer.generateSignature(data);

    ECDSASignature signature = new ECDSASignature(components[0], components[1]).toCanonicalised();

    // Now we have to work backwards to figure out the recId needed to recover the signature.
    int recId = -1;
    byte[] pubkey = PublicFromPrivateKey(privateKey);
    for (int i = 0; i < 4; i++) {
        byte[] k = recoverPubBytesFromSignature(i, signature, data);
        if (k != null && Arrays.equals(k, pubkey)) {
            recId = i;
            break;
        }
    }
    if (recId == -1) {
        throw new RuntimeException("Could not construct a recoverable key. This should never happen.");
    }
    signature.v = (byte) (recId + 27);

    return signature.toByteArray();

}
 
Example 12
Source File: ECKey.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Signs the given hash and returns the R and S components as BigIntegers and putData them in
 * ECDSASignature
 *
 * @param input to sign
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
    if (input.length != 32) {
        throw new IllegalArgumentException("Expected 32 byte input to " +
                "ECDSA signature, not " + input.length);
    }
    // No decryption of private key required.
    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (privKey instanceof BCECPrivateKey) {
        ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new
                SHA256Digest()));
        ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters
                (((BCECPrivateKey) privKey).getD(), CURVE);
        signer.init(true, privKeyParams);
        BigInteger[] components = signer.generateSignature(input);
        return new ECDSASignature(components[0], components[1])
                .toCanonicalised();
    } else {
        try {
            final Signature ecSig = ECSignatureFactory.getRawInstance
                    (provider);
            ecSig.initSign(privKey);
            ecSig.update(input);
            final byte[] derSignature = ecSig.sign();
            return ECDSASignature.decodeFromDER(derSignature)
                    .toCanonicalised();
        } catch (SignatureException | InvalidKeyException ex) {
            throw new RuntimeException("ECKey signing error", ex);
        }
    }
}
 
Example 13
Source File: ECKey.java    From nuls with MIT License 5 votes vote down vote up
protected byte[] doSign(byte[] input, BigInteger privateKeyForSigning) {
    Util.checkNotNull(privateKeyForSigning);
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE);
    signer.init(true, privKey);
    BigInteger[] components = signer.generateSignature(input);
    return new ECDSASignature(components[0], components[1]).toCanonicalised().encodeToDER();
}
 
Example 14
Source File: ECKey.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public ECDSASignature sign(Sha256Hash input) {
  ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
  ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(priv, CURVE);
  signer.init(true, privKey);
  BigInteger[] components = signer.generateSignature(input.getBytes());
  return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
 
Example 15
Source File: ECKey.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public ECDSASignature sign(Sha256Hash input) {
  ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
  ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(priv, CURVE);
  signer.init(true, privKey);
  BigInteger[] components = signer.generateSignature(input.getBytes());
  return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
 
Example 16
Source File: ECKey.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public ECDSASignature sign(Sha256Hash input) {
  ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
  ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(priv, CURVE);
  signer.init(true, privKey);
  BigInteger[] components = signer.generateSignature(input.getBytes());
  return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
 
Example 17
Source File: ECKey.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public ECDSASignature sign(Sha256Hash input) {
  ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
  ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(priv, CURVE);
  signer.init(true, privKey);
  BigInteger[] components = signer.generateSignature(input.getBytes());
  return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
 
Example 18
Source File: ECKey.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 * Signs the given hash and returns the R and S components as BigIntegers 
 * and put them in ECDSASignature 
 * 
 * @param input to sign
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
    // No decryption of private key required.
    if (priv == null)
        throw new MissingPrivateKeyException();
    check(priv != null, "Private key must not be null");
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(priv, CURVE);
    signer.init(true, privKey);
    BigInteger[] components = signer.generateSignature(input);
    return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
 
Example 19
Source File: SignUtils.java    From java-client with Apache License 2.0 4 votes vote down vote up
private static void sign(IntermediaryTransaction unsignedTransaction, List<String> privateKeys, boolean isHex, boolean addPubKey) {
    X9ECParameters params = SECNamedCurves.getByName("secp256k1");
    ECDomainParameters CURVE = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH());
    BigInteger HALF_CURVE_ORDER = params.getN().shiftRight(1);

    for (int i = 0; i < unsignedTransaction.getTosign().size(); i++) {
        String toSign = unsignedTransaction.getTosign().get(i);

        String privateKey = privateKeys.get(i);
        byte[] bytes;
        boolean compressed = false;
        if (isHex) {
            // nothing to do
            bytes = Hex.decode(privateKey);
        } else {
            bytes = getBytesFromBase58Key(privateKey);
        }
        if (bytes.length == 33 && bytes[32] == 1) {
            compressed = true;
            bytes = Arrays.copyOf(bytes, 32);  // Chop off the additional marker byte.
        }
        BigInteger privKeyB = new BigInteger(1, bytes);

        ECPoint point = CURVE.getG().multiply(privKeyB);
        if (compressed) {
            point = new ECPoint.Fp(CURVE.getCurve(), point.getX(), point.getY(), true);
        }

        byte[] publicKey = point.getEncoded();

        ECDSASigner signer = new ECDSASigner();
        ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privKeyB, CURVE);
        signer.init(true, privKey);


        if (addPubKey) {
            logger.info("Pushing Pub key for input");
            unsignedTransaction.addPubKeys(bytesToHexString(publicKey));
        }
        BigInteger[] components = signer.generateSignature(Hex.decode(toSign));
        BigInteger r = components[0];
        BigInteger s = components[1];
        // ensure Canonical
        s = ensureCanonical(s, HALF_CURVE_ORDER, CURVE);
        String signedString = bytesToHexString(toDER(r, s));
        unsignedTransaction.addSignature(signedString);
    }
}
 
Example 20
Source File: ECKey.java    From wkcwallet-java with Apache License 2.0 3 votes vote down vote up
/**
 * <p>
 * Verifies the given ECDSA signature against the message bytes using the
 * public key bytes.
 * </p>
 *
 * <p>
 * When using native ECDSA verification, data must be 32 bytes, and no
 * element may be larger than 520 bytes.
 * </p>
 *
 * @param data
 *            Hash of the data to verify.
 * @param signature
 *            signature.
 * @param pub
 *            The public key bytes to use.
 *
 * @return -
 */
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) {
    ECDSASigner signer = new ECDSASigner();
    ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pub), CURVE);
    signer.init(false, params);
    try {
        return signer.verifySignature(data, signature.r, signature.s);
    } catch (NullPointerException npe) {
        // Bouncy Castle contains a bug that can cause NPEs given specially
        // crafted signatures.
        // Those signatures are inherently invalid/attack sigs so we just
        // fail them here rather than crash the thread.
        return false;
    }
}