org.spongycastle.crypto.signers.ECDSASigner Java Examples

The following examples show how to use org.spongycastle.crypto.signers.ECDSASigner. 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 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 #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 green_android 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 #5
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 #6
Source File: BTCUtils.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 6 votes vote down vote up
public static boolean verify(byte[] publicKey, byte[] signature, byte[] msg) {
    X9ECParameters params = SECNamedCurves.getByName("secp256k1");
    ECDomainParameters EC_PARAMS = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH());
    synchronized (EC_PARAMS) {
        boolean valid;
        ECDSASigner signerVer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        try {
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(EC_PARAMS.getCurve().decodePoint(publicKey), EC_PARAMS);
            signerVer.init(false, pubKey);
            ASN1InputStream derSigStream = new ASN1InputStream(signature);
            DLSequence seq = (DLSequence) derSigStream.readObject();
            BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
            BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
            derSigStream.close();
            valid = signerVer.verifySignature(msg, r, s);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return valid;
    }
}
 
Example #7
Source File: ECKey.java    From gsc-core with GNU Lesser 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> <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 #8
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 #9
Source File: Secp256k1.java    From neb.java with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static boolean Verify(byte[] data, byte[] sign, byte[] pub) {
    if (data.length != 32) {
        throw new IllegalArgumentException("Expected 32 byte input to ECDSA verify, not " + data.length);
    }
    if (sign.length != 65) {
        throw new IllegalArgumentException("Expected 65 byte input of signature to ECDSA verify, not " + sign.length);
    }

    ECDSASignature signature = ECDSASignature.fromBytes(sign);

    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;
    }
}
 
Example #10
Source File: ECKeySecp256k1.java    From aion with MIT License 6 votes vote down vote up
/**
 * Verifies the given ECDSA signature against the message bytes using the public key bytes.
 *
 * <p>When using native ECDSA verification, data must be 32 bytes, and no element may be larger
 * than 520 bytes.
 *
 * @param data Hash of the data to verify.
 * @param signature signature.
 * @param pub The public key bytes to use.
 * @return -
 */
public 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 #11
Source File: ECKey.java    From bcm-android 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 #12
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 #13
Source File: NamedCurve.java    From UAF with Apache License 2.0 5 votes vote down vote up
/**
 * UAF_ALG_SIGN_SECP256R1_ECDSA_SHA256_RAW 0x01
 * An ECDSA signature on the NIST secp256r1 curve which MUST have raw R and S buffers, encoded in big-endian order.
 * I.e. [R (32 bytes), S (32 bytes)]
 * 
 * @param priv - Private key
 * @param input - Data to sign 
 * @return BigInteger[] - [R,S]
 */
public static BigInteger[] signAndFromatToRS(PrivateKey priv, byte[] input) {
	X9ECParameters params = SECNamedCurves.getByName("secp256r1");
	ECDomainParameters ecParams = new ECDomainParameters(params.getCurve(),
			params.getG(), params.getN(), params.getH());
	if (priv == null)
		throw new IllegalStateException(
				"This ECKey does not have the private key necessary for signing.");
	ECDSASigner signer = new ECDSASigner();
	ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
			((ECPrivateKey) priv).getS(), ecParams);
	signer.init(true, privKey);
	BigInteger[] sigs = signer.generateSignature(input);
	return sigs;
}
 
Example #14
Source File: ECKeySecp256k1.java    From aion 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) {
    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 #15
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 #16
Source File: ECKey.java    From nuls with MIT License 5 votes vote down vote up
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 e) {
        log.error("Caught NPE inside bouncy castle", e);
        return false;
    }
}
 
Example #17
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 #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: 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 #20
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 #21
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 #22
Source File: EthECKeyPair.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 5 votes vote down vote up
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.
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(priv, domain);
    signer.init(true, privKeyParams);
    BigInteger[] components = signer.generateSignature(input);
    return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
 
Example #23
Source File: ECDSAAlgorithm.java    From md_blockchain with Apache License 2.0 5 votes vote down vote up
public static String sign(String privateKey, byte[] data) {
    byte[] hash256 = BaseAlgorithm.encode("SHA-256", data);
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    BigInteger pri = new BigInteger(1, Base64.decodeBase64(privateKey));
    ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(pri, CURVE);
    signer.init(true, privKey);
    BigInteger[] components = signer.generateSignature(hash256);
    byte[] content = new ECDSASignature(components[0], components[1]).toCanonicalised().encodeToDER();
    String result = Base64.encodeBase64String(content);
    result = result.replaceAll("[\\s*\t\n\r]", "");
    return result;
}
 
Example #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
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);
    }
}