org.spongycastle.crypto.digests.SHA256Digest Java Examples

The following examples show how to use org.spongycastle.crypto.digests.SHA256Digest. 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: 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 #2
Source File: types.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String toString() {
    byte[] data = new byte[key_data.length + 1 + 4];
    data[0] = (byte) 0x80;
    System.arraycopy(key_data, 0, data, 1, key_data.length);

    SHA256Digest digest = new SHA256Digest();
    digest.update(data, 0, key_data.length + 1);
    byte[] out = new byte[32];
    digest.doFinal(out, 0);

    digest.update(out, 0, out.length);
    digest.doFinal(out, 0);

    System.arraycopy(out, 0, data, key_data.length + 1, 4);
    return Base58.encode(data);
}
 
Example #3
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 #4
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 #5
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 #6
Source File: wallet_api.java    From bitshares_wallet with MIT License 6 votes vote down vote up
private private_key derive_private_key(String strWifKey, int nSeqNumber) {
    String strData = strWifKey + " " + nSeqNumber;
    byte[] bytesBuffer = strData.getBytes();
    SHA512Digest digest = new SHA512Digest();
    digest.update(bytesBuffer, 0, bytesBuffer.length);

    byte[] out = new byte[64];
    digest.doFinal(out, 0);

    SHA256Digest digest256 = new SHA256Digest();
    byte[] outSeed = new byte[32];
    digest256.update(out, 0, out.length);
    digest.doFinal(outSeed, 0);

    return new private_key(outSeed);
}
 
Example #7
Source File: types.java    From bitshares_wallet with MIT License 6 votes vote down vote up
@Override
public String toString() {
    byte[] data = new byte[key_data.length + 1 + 4];
    data[0] = (byte)0x80;
    System.arraycopy(key_data, 0, data, 1, key_data.length);

    SHA256Digest digest = new SHA256Digest();
    digest.update(data, 0, key_data.length + 1);
    byte[] out = new byte[32];
    digest.doFinal(out, 0);

    digest.update(out, 0, out.length);
    digest.doFinal(out, 0);

    System.arraycopy(out, 0, data, key_data.length + 1, 4);
    return Base58.encode(data);
}
 
Example #8
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 #9
Source File: wallet_api.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private private_key derive_private_key(String strWifKey, int nSeqNumber) {
    String strData = strWifKey + " " + nSeqNumber;
    byte[] bytesBuffer = strData.getBytes();
    SHA512Digest digest = new SHA512Digest();
    digest.update(bytesBuffer, 0, bytesBuffer.length);

    byte[] out = new byte[64];
    digest.doFinal(out, 0);

    SHA256Digest digest256 = new SHA256Digest();
    byte[] outSeed = new byte[32];
    digest256.update(out, 0, out.length);
    digest.doFinal(outSeed, 0);

    return new private_key(outSeed);
}
 
Example #10
Source File: ECIESCoder.java    From wkcwallet-java with Apache License 2.0 6 votes vote down vote up
public static byte[] decrypt(ECPoint ephem, BigInteger prv, byte[] IV, byte[] cipher, byte[] macData) throws InvalidCipherTextException {
    AESFastEngine aesFastEngine = new AESFastEngine();

    EthereumIESEngine iesEngine = new EthereumIESEngine(
            new ECDHBasicAgreement(),
            new ConcatKDFBytesGenerator(new SHA256Digest()),
            new HMac(new SHA256Digest()),
            new SHA256Digest(),
            new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));


    byte[]         d = new byte[] {};
    byte[]         e = new byte[] {};

    IESParameters p = new IESWithCipherParameters(d, e, KEY_SIZE, KEY_SIZE);
    ParametersWithIV parametersWithIV =
            new ParametersWithIV(p, IV);

    iesEngine.init(false, new ECPrivateKeyParameters(prv, CURVE), new ECPublicKeyParameters(ephem, CURVE), parametersWithIV);

    return iesEngine.processBlock(cipher, 0, cipher.length, macData);
}
 
Example #11
Source File: types.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String toString() {
    byte[] data = new byte[key_data.length + 1 + 4];
    data[0] = (byte)0x80;
    System.arraycopy(key_data, 0, data, 1, key_data.length);

    SHA256Digest digest = new SHA256Digest();
    digest.update(data, 0, key_data.length + 1);
    byte[] out = new byte[32];
    digest.doFinal(out, 0);

    digest.update(out, 0, out.length);
    digest.doFinal(out, 0);

    System.arraycopy(out, 0, data, key_data.length + 1, 4);
    return Base58.encode(data);
}
 
Example #12
Source File: ECIESCoder.java    From wkcwallet-java with Apache License 2.0 6 votes vote down vote up
private static EthereumIESEngine makeIESEngine(boolean isEncrypt, ECPoint pub, BigInteger prv, byte[] IV) {
    AESFastEngine aesFastEngine = new AESFastEngine();

    EthereumIESEngine iesEngine = new EthereumIESEngine(
            new ECDHBasicAgreement(),
            new ConcatKDFBytesGenerator(new SHA256Digest()),
            new HMac(new SHA256Digest()),
            new SHA256Digest(),
            new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));


    byte[]         d = new byte[] {};
    byte[]         e = new byte[] {};

    IESParameters p = new IESWithCipherParameters(d, e, KEY_SIZE, KEY_SIZE);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, IV);

    iesEngine.init(isEncrypt, new ECPrivateKeyParameters(prv, CURVE), new ECPublicKeyParameters(pub, CURVE), parametersWithIV);
    return iesEngine;
}
 
Example #13
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 #14
Source File: LWallet.java    From dapp-wallet-demo with Apache License 2.0 5 votes vote down vote up
private static byte[] generateAes128CtrDerivedKey(
        byte[] password, byte[] salt, int c, String prf) throws CipherException {

    if (!prf.equals("hmac-sha256")) {
        throw new CipherException("Unsupported prf:" + prf);
    }

    // Java 8 supports this, but you have to convert the password to a character array, see
    // http://stackoverflow.com/a/27928435/3211687

    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
    gen.init(password, salt, c);
    return ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
}
 
Example #15
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 #16
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 #17
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 #18
Source File: sha256_object.java    From bitshares_wallet with MIT License 5 votes vote down vote up
public static sha256_object create_from_string(String strContent) {
    SHA256Digest digest = new SHA256Digest();
    byte[] bytePassword = strContent.getBytes();
    digest.update(bytePassword, 0, bytePassword.length);

    byte[] byteHash = new byte[32];
    digest.doFinal(byteHash, 0);

    sha256_object sha256Object = new sha256_object();
    System.arraycopy(byteHash, 0, sha256Object.hash, 0, byteHash.length);

    return sha256Object;
}
 
Example #19
Source File: types.java    From bitshares_wallet with MIT License 5 votes vote down vote up
public private_key_type(String strBase58) {
    byte wif_bytes[] = Base58.decode(strBase58);
    if (wif_bytes.length < 5) {
        throw new RuntimeException("Private key is not valid");
    }

    System.arraycopy(wif_bytes, 1, key_data, 0, key_data.length);

    SHA256Digest digest = new SHA256Digest();
    digest.update(wif_bytes, 0, wif_bytes.length - 4);
    byte[] hashCheck = new byte[32];
    digest.doFinal(hashCheck, 0);

    byte[] hashCheck2 = new byte[32];
    digest.update(hashCheck, 0, hashCheck.length);
    digest.doFinal(hashCheck2, 0);

    byte check[] = new byte[4];
    System.arraycopy(wif_bytes, wif_bytes.length - check.length, check, 0, check.length);

    byte[] check1 = new byte[4];
    byte[] check2 = new byte[4];
    System.arraycopy(hashCheck, 0, check1, 0, check1.length);
    System.arraycopy(hashCheck2, 0, check2, 0, check2.length);

    if (Arrays.equals(check1, check) == false &&
            Arrays.equals(check2, check) == false) {
        throw new RuntimeException("Private key is not valid");
    }
}
 
Example #20
Source File: CryptoPrimitivesAndroid.java    From Clusion with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] generateHmac(byte[] key, String msg) throws UnsupportedEncodingException {

		HMac hmac = new HMac(new SHA256Digest());
		byte[] result = new byte[hmac.getMacSize()];
		byte[] msgAry = msg.getBytes("UTF-8");
		hmac.init(new KeyParameter(key));
		hmac.reset();
		hmac.update(msgAry, 0, msgAry.length);
		hmac.doFinal(result, 0);
		return result;
	}
 
Example #21
Source File: CryptoPrimitivesAndroid.java    From Clusion with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] generateHmac(byte[] key, byte[] msg) throws UnsupportedEncodingException {

		HMac hmac = new HMac(new SHA256Digest());
		byte[] result = new byte[hmac.getMacSize()];
		hmac.init(new KeyParameter(key));
		hmac.reset();
		hmac.update(msg, 0, msg.length);
		hmac.doFinal(result, 0);
		return result;
	}
 
Example #22
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 #23
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 #24
Source File: sha256_object.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
public static sha256_object create_from_string(String strContent) {
    SHA256Digest digest = new SHA256Digest();
    byte[] bytePassword = strContent.getBytes();
    digest.update(bytePassword, 0, bytePassword.length);

    byte[] byteHash = new byte[32];
    digest.doFinal(byteHash, 0);

    sha256_object sha256Object = new sha256_object();
    System.arraycopy(byteHash, 0, sha256Object.hash, 0, byteHash.length);

    return sha256Object;
}
 
Example #25
Source File: types.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
public private_key_type(String strBase58) throws KeyInvalideException, AddressFormatException {
    byte wif_bytes[] = Base58.decode(strBase58);

    if (wif_bytes.length < key_data.length) {
        throw new KeyInvalideException("Private key is not valid");
    }
    System.arraycopy(wif_bytes, 1, key_data, 0, key_data.length);
    SHA256Digest digest = new SHA256Digest();
    digest.update(wif_bytes, 0, wif_bytes.length - 4);
    byte[] hashCheck = new byte[32];
    digest.doFinal(hashCheck, 0);

    byte[] hashCheck2 = new byte[32];
    digest.update(hashCheck, 0, hashCheck.length);
    digest.doFinal(hashCheck2, 0);

    byte check[] = new byte[4];
    System.arraycopy(wif_bytes, wif_bytes.length - check.length, check, 0, check.length);

    byte[] check1 = new byte[4];
    byte[] check2 = new byte[4];
    System.arraycopy(hashCheck, 0, check1, 0, check1.length);
    System.arraycopy(hashCheck2, 0, check2, 0, check2.length);
    if (!Arrays.equals(check1, check) && !Arrays.equals(check2, check)) {
        throw new KeyInvalideException("Private key is not valid");
    }
}
 
Example #26
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 #27
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 #28
Source File: PBKDF2Crypto.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] generateDerivedKey(byte[] password) {
  PBKDF2Params params = this.kdfparams;
  if (!PBKDF2Params.PRF.equals(params.getPrf())) {
    throw new TokenException(Messages.PRF_UNSUPPORTED);
  }

  PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new SHA256Digest());
  generator.init(password, NumericUtil.hexToBytes(params.getSalt()), params.getC());
  return ((KeyParameter) generator.generateDerivedParameters(256)).getKey();
}
 
Example #29
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 #30
Source File: PBKDFTest.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
@Test
public void derive() {
  for (String[] example : PBKDFExample) {
    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
    gen.init(example[3].getBytes(), example[0].getBytes(), Integer.parseInt(example[1]));
    byte[] derivedKey = ((KeyParameter) gen.generateDerivedParameters(Integer.parseInt(example[2]) * 8)).getKey();
    Assert.assertEquals(NumericUtil.bytesToHex(derivedKey), example[4]);
  }
}