org.spongycastle.crypto.params.ECPrivateKeyParameters Java Examples

The following examples show how to use org.spongycastle.crypto.params.ECPrivateKeyParameters. 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: EOSECDSASigner.java    From token-core-android with Apache License 2.0 6 votes vote down vote up
public void init(
    boolean forSigning,
    CipherParameters param) {
  SecureRandom providedRandom = null;

  if (forSigning) {
    if (param instanceof ParametersWithRandom) {
      ParametersWithRandom rParam = (ParametersWithRandom) param;

      this.key = (ECPrivateKeyParameters) rParam.getParameters();
      providedRandom = rParam.getRandom();
    } else {
      this.key = (ECPrivateKeyParameters) param;
    }
  } else {
    this.key = (ECPublicKeyParameters) param;
  }

  this.random = initSecureRandom(forSigning && !kCalculator.isDeterministic(), providedRandom);
}
 
Example #2
Source File: ECKeyPair.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 6 votes vote down vote up
public static ECKeyPair createNew(boolean compressed) {
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(domain,
            secureRandom);
    generator.init(keygenParams);
    AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
    ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
    ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic();
    ECKeyPair k = new ECKeyPair();
    k.priv = privParams.getD();
    k.compressed = compressed;
    ECPoint multiply = CURVE.getG().multiply(k.priv);
    k.pub = multiply.getEncoded(false);
    k.pubComp = multiply.getEncoded(true);
    return k;
}
 
Example #3
Source File: Secp256k1.java    From neb.java with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static byte[] GenerateECKey() {
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(CURVE, Utils.SecureRandom());
    generator.init(keygenParams);
    AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
    ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
    BigInteger privKey = privParams.getD();
    return ByteUtils.BigIntegerToBytes(privKey, 32);
}
 
Example #4
Source File: ECKeyPair.java    From bitseal with GNU General Public License v3.0 5 votes vote down vote up
/** 
 * Generates an entirely new keypair. 
 * */
public ECKeyPair() 
{
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(ecParams, secureRandom);
    generator.init(keygenParams);
    AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
    ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
    ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic();
    priv = privParams.getD();
    pub = pubParams.getQ().getEncoded();// The public key is an encoded point on the elliptic curve. It has no meaning independent of the curve.
}
 
Example #5
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 #6
Source File: ECKey.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 * Generates an entirely new keypair with the given {@link SecureRandom} object. Point compression is used so the
 * resulting public key will be 33 bytes (32 for the co-ordinate and 1 byte to represent the y bit).
 */
public ECKey(SecureRandom secureRandom) {
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(CURVE, secureRandom);
    generator.init(keygenParams);
    AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
    ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
    ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic();
    priv = privParams.getD();
    pub = CURVE.getCurve().decodePoint(pubParams.getQ().getEncoded(true));
}
 
Example #7
Source File: ECKey.java    From bitherj with Apache License 2.0 5 votes vote down vote up
/**
 * Generates an entirely new keypair. Point compression is used so the resulting public key will be 33 bytes
 * (32 for the co-ordinate and 1 byte to represent the y bit).
 */
public static ECKey generateECKey(SecureRandom secureRandom) {

    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(CURVE, secureRandom);
    generator.init(keygenParams);
    AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
    ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
    ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic();
    BigInteger priv = privParams.getD();
    boolean compressed = true;
    ECKey ecKey = new ECKey(priv, pubParams.getQ().getEncoded(compressed));
    ecKey.setCreationTimeSeconds(Utils.currentTimeSeconds());
    return ecKey;
}
 
Example #8
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 #9
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 #10
Source File: ECKey.java    From nuls with MIT License 5 votes vote down vote up
public ECKey(SecureRandom secureRandom) {
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(CURVE, secureRandom);
    generator.init(keygenParams);
    AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
    ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
    ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic();
    priv = privParams.getD();
    pub = pubParams.getQ();
    creationTimeSeconds = System.currentTimeMillis();
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #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 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 #19
Source File: EOSSign.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
private static ECKey.ECDSASignature eosSign(byte[] input, BigInteger privateKeyForSigning) {
  EOSECDSASigner signer = new EOSECDSASigner(new MyHMacDSAKCalculator(new SHA256Digest()));
  ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE);
  signer.init(true, privKey);
  BigInteger[] components = signer.generateSignature(input);
  return new ECKey.ECDSASignature(components[0], components[1]).toCanonicalised();
}
 
Example #20
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 #21
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 #22
Source File: EOSECDSASigner.java    From token-core-android with Apache License 2.0 4 votes vote down vote up
/**
 * generate a signature for the given message using the key we were
 * initialised with. For conventional DSA the message should be a SHA-1
 * hash of the message of interest.
 *
 * @param message the message that will be verified later.
 */
public BigInteger[] generateSignature(
    byte[] message) {
  ECDomainParameters ec = key.getParameters();
  BigInteger n = ec.getN();
  BigInteger e = calculateE(n, message);
  BigInteger d = ((ECPrivateKeyParameters) key).getD();

  int nonce = 1;
  BigInteger r, s;
  while (true) {

    kCalculator.init(n, d, message);
    ECMultiplier basePointMultiplier = createBasePointMultiplier();

    // 5.3.2
    do // generate s
    {
      BigInteger k = BigInteger.ZERO;
      do // generate r
      {
        k = kCalculator.nextK();
        for (int i = 0; i < nonce; i++) {
          k = kCalculator.nextK();
        }

        ECPoint p = basePointMultiplier.multiply(ec.getG(), k).normalize();

        // 5.3.3
        r = p.getAffineXCoord().toBigInteger().mod(n);
      }
      while (r.equals(ZERO));

    // Compute s = (k^-1)*(h + Kx*privkey)
      s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n);
    }
    while (s.equals(ZERO));

    byte[] der = new ECKey.ECDSASignature(r, s).toCanonicalised().encodeToDER();

    int lenR = der[3];
    int lenS = der[5 + lenR];
    if (lenR == 32 && lenS == 32) {
      break;
    }
    nonce++;
  }

  return new BigInteger[]{r, s};
}
 
Example #23
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);
    }
}