Java Code Examples for org.bouncycastle.crypto.digests.SHA256Digest

The following examples show how to use org.bouncycastle.crypto.digests.SHA256Digest. These examples are extracted from open source projects. 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
public static void main(String[] args) {

        try {
            OntSdk ontSdk = getOntSdk();

            com.github.ontio.account.Account account = new com.github.ontio.account.Account(Helper.hexToBytes("9a31d585431ce0aa0aab1f0a432142e98a92afccb7bcbcaff53f758df82acdb3"), ontSdk.defaultSignScheme);
            System.out.println("PrivateKey:"+Helper.toHexString(account.serializePrivateKey()));
            System.out.println("PublicKey:"+Helper.toHexString(account.serializePublicKey()));
//            System.out.println(Helper.toHexString(account.serializePrivateKey()));

            //setDigest
            ECIES.setDigest(new SHA256Digest());
            byte[] msg = new String("1234567890").getBytes();
            String[] ret = ECIES.Encrypt(Helper.toHexString(account.serializePublicKey()),msg);
            byte[] msg2 = ECIES.Decrypt(Helper.toHexString(account.serializePrivateKey()),ret);
//            byte[] msg3 = ECIES.Decrypt(account,ret);
            System.out.println("Msg:"+Helper.toHexString(msg));
            System.out.println("Encrypted:"+JSON.toJSONString(ret));
            System.out.println("Decrypt:"+Helper.toHexString(msg2));
//            System.out.println(Helper.toHexString(msg3));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
 
Example 2
Source Project: localization_nifi   Source File: PBKDF2CipherProvider.java    License: Apache License 2.0 6 votes vote down vote up
private Digest resolvePRF(final String prf) {
    if (StringUtils.isEmpty(prf)) {
        throw new IllegalArgumentException("Cannot resolve empty PRF");
    }
    String formattedPRF = prf.toLowerCase().replaceAll("[\\W]+", "");
    logger.debug("Resolved PRF {} to {}", prf, formattedPRF);
    switch (formattedPRF) {
        case "md5":
            return new MD5Digest();
        case "sha1":
            return new SHA1Digest();
        case "sha384":
            return new SHA384Digest();
        case "sha256":
            return new SHA256Digest();
        case "sha512":
            return new SHA512Digest();
        default:
            logger.warn("Could not resolve PRF {}. Using default PRF {} instead", prf, DEFAULT_PRF);
            return new SHA512Digest();
    }
}
 
Example 3
Source Project: nuls-v2   Source File: HMacTest.java    License: MIT License 6 votes vote down vote up
@Test
public void test() {
    String iv = "00000000000000000000000000000000";
    String pubKeyA = "0410baeeb267e1d680adf4e2ad0eb61b6a3173657971c0209425406883f09ac639c7dad2baf8ab2d66e6b64c3cbd4dd488de91cc47b5ead45db299a929c4ebd468";
    String ciphertext = "b4d6ecbd61b3630abf609e102fcbd125";
    String dataToMac = iv + pubKeyA + ciphertext;
    String macKey = "785ac461b5c8607c39ec4f63e1004f19a77c371e6f91293f66d4c19c02524265";
    HMac mac = new HMac(new SHA256Digest());
    mac.init(new KeyParameter(HexUtil.decode(macKey)));

    byte[] byteArray = HexUtil.decode(dataToMac);
    mac.update(byteArray, 0, byteArray.length);
    byte[] macOutput = new byte[mac.getMacSize()];
    mac.doFinal(macOutput, 0);
    System.out.println(HexUtil.encode(macOutput));
    // hmac hex string: bcf0e6f47bf5622e3596104f4d1bcd0bc4f643a196f0520be834bb0b4d1043fa
}
 
Example 4
Source Project: evt4j   Source File: Signature.java    License: MIT License 6 votes vote down vote up
public static Signature signHash(byte[] hash, @NotNull PrivateKey key) {
    checkHashLength(hash);

    // init deterministic k calculator
    Signer signer = new Signer(new HMacDSAKCalculator(new SHA256Digest()));
    ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(key.getD(), ECKey.CURVE);

    signer.init(true, privateKeyParameters);
    BigInteger[] components = signer.generateSignature(hash);

    Signature sig = new Signature(components[0], components[1]).toCanonicalised();

    // find the recId and store in signature for public key recover later
    PublicKey publicKey = key.toPublicKey();
    int recId = getRecId(sig, hash, publicKey);

    if (recId == -1) {
        throw new RecoverIDNotFoundException();
    }

    sig.setRecId(recId);

    return sig;
}
 
Example 5
Source Project: fabric-sdk-java   Source File: Endpoint.java    License: Apache License 2.0 6 votes vote down vote up
byte[] getClientTLSCertificateDigest() {
    //The digest must be SHA256 over the DER encoded certificate. The PEM has the exact DER sequence in hex encoding around the begin and end markers

    if (tlsClientCertificatePEMBytes != null && clientTLSCertificateDigest == null) {

        String pemCert = new String(tlsClientCertificatePEMBytes, UTF_8);
        byte[] derBytes = Base64.getDecoder().decode(
                pemCert.replaceAll("-+[ \t]*(BEGIN|END)[ \t]+CERTIFICATE[ \t]*-+", "").replaceAll("\\s", "").trim()
        );

        Digest digest = new SHA256Digest();
        clientTLSCertificateDigest = new byte[digest.getDigestSize()];
        digest.update(derBytes, 0, derBytes.length);
        digest.doFinal(clientTLSCertificateDigest, 0);
    }

    return clientTLSCertificateDigest;
}
 
Example 6
Source Project: fabric-api-archive   Source File: BouncyCastleCrypto.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] sign(byte[] hash, byte[] privateKey) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    signer.init(true, new ECPrivateKeyParameters(new BigInteger(privateKey), domain));
    BigInteger[] signature = signer.generateSignature(hash);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        DERSequenceGenerator seq = new DERSequenceGenerator(baos);
        seq.addObject(new ASN1Integer(signature[0]));
        seq.addObject(new ASN1Integer(toCanonicalS(signature[1])));
        seq.close();
        return baos.toByteArray();
    } catch (IOException e) {
        return new byte[0];
    }
}
 
Example 7
Source Project: webpush-java   Source File: HttpEce.java    License: MIT License 6 votes vote down vote up
/**
 * Convenience method for computing the HMAC Key Derivation Function. The real work is offloaded to BouncyCastle.
 */
protected static byte[] hkdfExpand(byte[] ikm, byte[] salt, byte[] info, int length) {
    log("salt", salt);
    log("ikm", ikm);
    log("info", info);

    HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA256Digest());
    hkdf.init(new HKDFParameters(ikm, salt, info));

    byte[] okm = new byte[length];
    hkdf.generateBytes(okm, 0, length);

    log("expand", okm);

    return okm;
}
 
Example 8
Source Project: fabric-api   Source File: BouncyCastleCrypto.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] sign(byte[] hash, byte[] privateKey) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    signer.init(true, new ECPrivateKeyParameters(new BigInteger(privateKey), domain));
    BigInteger[] signature = signer.generateSignature(hash);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        DERSequenceGenerator seq = new DERSequenceGenerator(baos);
        seq.addObject(new ASN1Integer(signature[0]));
        seq.addObject(new ASN1Integer(toCanonicalS(signature[1])));
        seq.close();
        return baos.toByteArray();
    } catch (IOException e) {
        return new byte[0];
    }
}
 
Example 9
Source Project: InflatableDonkey   Source File: EscrowOperationsRecover.java    License: MIT License 6 votes vote down vote up
static NSDictionary decrypt(BlobA6 blob, byte[] key) {
    logger.debug("-- decrypt() - response blob: {}", blob);

    byte[] pcsData = AESCBC.decryptAESCBC(key, blob.iv(), blob.data());
    logger.debug("-- decrypt() - pcs data: 0x{}", Hex.toHexString(pcsData));

    BlobA0 pcsBlob = new BlobA0(ByteBuffer.wrap(pcsData));
    logger.debug("-- decrypt() - pcs blob: {}", pcsBlob);

    byte[] derivedKey
            = PBKDF2.generate(new SHA256Digest(), pcsBlob.dsid(), pcsBlob.salt(), pcsBlob.iterations(), 16 * 8);
    logger.debug("-- decrypt() - derived key: 0x{}", Hex.toHexString(derivedKey));

    byte[] saltIV = Arrays.copyOf(pcsBlob.salt(), 0x10);
    logger.debug("-- decrypt() - salt/ iv: 0x{}", Hex.toHexString(saltIV));

    byte[] dictionaryData = AESCBC.decryptAESCBC(derivedKey, saltIV, pcsBlob.data());
    logger.debug("-- decrypt() - dictionary data: 0x{}", Hex.toHexString(dictionaryData));

    NSDictionary dictionary = PListsLegacy.parseDictionary(dictionaryData);
    logger.debug("-- decrypt() - dictionary: {}", dictionary.toXMLPropertyList());
    return dictionary;
}
 
Example 10
Source Project: InflatableDonkey   Source File: KeyBlobCurve25519Unwrap.java    License: MIT License 6 votes vote down vote up
public static Optional<byte[]> curve25519Unwrap(
        byte[] myPublicKey,
        byte[] myPrivateKey,
        byte[] otherPublicKey,
        byte[] wrappedKey) {

    SHA256Digest sha256 = new SHA256Digest();

    byte[] shared = Curve25519.agreement(otherPublicKey, myPrivateKey);
    logger.debug("-- curve25519Unwrap() - shared agreement: 0x{}", Hex.toHexString(shared));

    // Stripped down NIST SP 800-56A KDF.
    byte[] counter = new byte[]{0x00, 0x00, 0x00, 0x01};
    byte[] hash = new byte[sha256.getDigestSize()];

    sha256.reset();
    sha256.update(counter, 0, counter.length);
    sha256.update(shared, 0, shared.length);
    sha256.update(otherPublicKey, 0, otherPublicKey.length);
    sha256.update(myPublicKey, 0, myPublicKey.length);
    sha256.doFinal(hash, 0);

    logger.debug("-- curve25519Unwrap() - kek: {}", Hex.toHexString(hash));
    return RFC3394Wrap.unwrapAES(hash, wrappedKey);
}
 
Example 11
Source Project: bop-bitcoin-client   Source File: ECKeyPair.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] sign (byte[] hash) throws ValidationException
{
	if ( priv == null )
	{
		throw new ValidationException ("Need private key to sign");
	}
	ECDSASigner signer = new ECDSASigner (new HMacDSAKCalculator (new SHA256Digest ()));
	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 ASN1Integer (signature[0]));
		seq.addObject (new ASN1Integer (signature[1]));
		seq.close ();
		return s.toByteArray ();
	}
	catch ( IOException e )
	{
	}
	return null;
}
 
Example 12
@Override
public byte[] sign (byte[] hash) throws ValidationException
{
	if ( priv == null )
	{
		throw new ValidationException ("Need private key to sign");
	}
	ECDSASigner signer = new ECDSASigner (new HMacDSAKCalculator (new SHA256Digest ()));
	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 ASN1Integer (signature[0]));
		seq.addObject (new ASN1Integer (signature[1]));
		seq.close ();
		return s.toByteArray ();
	}
	catch ( IOException e )
	{
	}
	return null;
}
 
Example 13
public static void main(String args[]) {
    byte[] digest = new byte[4096];
    for (int i = 0; i < digest.length; i++) {
        digest[i] = (byte)i;
    }

    long start = JVM.monotonicTimeMillis();
    for (int i = 0; i < 20; i++) {
        SHA256Digest digester = new SHA256Digest();
        byte[] retValue = new byte[digester.getDigestSize()];
        for (int j = 0; j < UPDATES; j++) {
            digester.update(digest, 0, digest.length);
        }
        digester.doFinal(retValue, 0);
    }
    long time = JVM.monotonicTimeMillis() - start;
    System.out.println("BouncyCastleSHA256: " + time);
}
 
Example 14
public void test(TestHarness th) {
    SHA256Digest md = new SHA256Digest();
    byte[] retValue = new byte[md.getDigestSize()];

    for (int i = 0; i < messages.length; i++) {
        byte[] bytes = messages[i].getBytes();
        md.update(bytes, 0, bytes.length);
        md.doFinal(retValue, 0);
        th.check(Util.hexEncode(retValue).toLowerCase(), digests[i]);
    }

    for (int i = 0; i < 1000000; i++) {
        md.update((byte)'a');
    }
    md.doFinal(retValue, 0);
    th.check(Util.hexEncode(retValue).toLowerCase(), MILLION_A_DIGEST);
}
 
Example 15
Source Project: nifi   Source File: PBKDF2CipherProvider.java    License: Apache License 2.0 6 votes vote down vote up
private Digest resolvePRF(final String prf) {
    if (StringUtils.isEmpty(prf)) {
        throw new IllegalArgumentException("Cannot resolve empty PRF");
    }
    String formattedPRF = prf.toLowerCase().replaceAll("[\\W]+", "");
    logger.debug("Resolved PRF {} to {}", prf, formattedPRF);
    switch (formattedPRF) {
        case "md5":
            return new MD5Digest();
        case "sha1":
            return new SHA1Digest();
        case "sha384":
            return new SHA384Digest();
        case "sha256":
            return new SHA256Digest();
        case "sha512":
            return new SHA512Digest();
        default:
            logger.warn("Could not resolve PRF {}. Using default PRF {} instead", prf, DEFAULT_PRF);
            return new SHA512Digest();
    }
}
 
Example 16
Source Project: incubator-tuweni   Source File: RLPxConnectionFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forEncryption(
    PublicKey pubKey,
    Bytes iv,
    Bytes commonMac,
    KeyPair ephemeralKeyPair) {
  CipherParameters pubParam = new ECPublicKeyParameters(pubKey.asEcPoint(), CURVE);
  CipherParameters privParam =
      new ECPrivateKeyParameters(ephemeralKeyPair.secretKey().bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agree = new ECDHBasicAgreement();
  agree.init(privParam);
  BigInteger z = agree.calculateAgreement(pubParam);
  byte[] zbytes = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  // Initialise the KDF.
  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(zbytes, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agree,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(true, privParam, pubParam, cipherParameters);

  return engine;
}
 
Example 17
Source Project: incubator-tuweni   Source File: RLPxConnectionFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forDecryption(
    SecretKey privateKey,
    PublicKey ephemeralPublicKey,
    Bytes iv,
    Bytes commonMac) {
  CipherParameters pubParam = new ECPublicKeyParameters(ephemeralPublicKey.asEcPoint(), CURVE);
  CipherParameters privParam = new ECPrivateKeyParameters(privateKey.bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agreement = new ECDHBasicAgreement();
  agreement.init(privParam);
  byte[] agreementValue =
      BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), agreement.calculateAgreement(pubParam));

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(agreementValue, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agreement,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(false, privParam, pubParam, cipherParameters);
  return engine;
}
 
Example 18
Source Project: besu   Source File: SECP256K1.java    License: Apache License 2.0 5 votes vote down vote up
private static Signature signDefault(final Bytes32 dataHash, final KeyPair keyPair) {
  final ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));

  final ECPrivateKeyParameters privKey =
      new ECPrivateKeyParameters(
          keyPair.getPrivateKey().getEncodedBytes().toUnsignedBigInteger(), CURVE);
  signer.init(true, privKey);

  final BigInteger[] components = signer.generateSignature(dataHash.toArrayUnsafe());

  return normaliseSignature(components[0], components[1], keyPair.getPublicKey(), dataHash);
}
 
Example 19
Source Project: netty-4.1.22   Source File: Digester.java    License: Apache License 2.0 5 votes vote down vote up
public static DigestCalculator sha256() {
    Digest digest = new SHA256Digest();

    // The OID for SHA-256: http://www.oid-info.com/get/2.16.840.1.101.3.4.2.1
    ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(
            "2.16.840.1.101.3.4.2.1").intern();
    AlgorithmIdentifier algId = new AlgorithmIdentifier(oid);

    return new Digester(digest, algId);
}
 
Example 20
Source Project: client-sdk-java   Source File: Wallet.java    License: 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 21
Source Project: client-sdk-java   Source File: ECKeyPair.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sign a hash with the private key of this key pair.
 * @param transactionHash   the hash to sign
 * @return  An {@link ECDSASignature} of the hash
 */
public ECDSASignature sign(byte[] transactionHash) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));

    ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKey, Sign.CURVE);
    signer.init(true, privKey);
    BigInteger[] components = signer.generateSignature(transactionHash);

    return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
 
Example 22
Source Project: etherscan-explorer   Source File: Wallet.java    License: GNU General Public License v3.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 23
Source Project: etherscan-explorer   Source File: ECKeyPair.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sign a hash with the private key of this key pair.
 * @param transactionHash   the hash to sign
 * @return  An {@link ECDSASignature} of the hash
 */
public ECDSASignature sign(byte[] transactionHash) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));

    ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKey, Sign.CURVE);
    signer.init(true, privKey);
    BigInteger[] components = signer.generateSignature(transactionHash);

    return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
 
Example 24
Source Project: cava   Source File: RLPxConnectionFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forEncryption(
    PublicKey pubKey,
    Bytes iv,
    Bytes commonMac,
    KeyPair ephemeralKeyPair) {
  CipherParameters pubParam = new ECPublicKeyParameters(pubKey.asEcPoint(), CURVE);
  CipherParameters privParam =
      new ECPrivateKeyParameters(ephemeralKeyPair.secretKey().bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agree = new ECDHBasicAgreement();
  agree.init(privParam);
  BigInteger z = agree.calculateAgreement(pubParam);
  byte[] zbytes = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  // Initialise the KDF.
  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(zbytes, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agree,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(true, privParam, pubParam, cipherParameters);

  return engine;
}
 
Example 25
Source Project: cava   Source File: RLPxConnectionFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forDecryption(
    SecretKey privateKey,
    PublicKey ephemeralPublicKey,
    Bytes iv,
    Bytes commonMac) {
  CipherParameters pubParam = new ECPublicKeyParameters(ephemeralPublicKey.asEcPoint(), CURVE);
  CipherParameters privParam = new ECPrivateKeyParameters(privateKey.bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agreement = new ECDHBasicAgreement();
  agreement.init(privParam);
  byte[] agreementValue =
      BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), agreement.calculateAgreement(pubParam));

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(agreementValue, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agreement,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(false, privParam, pubParam, cipherParameters);
  return engine;
}
 
Example 26
Source Project: nuls-v2   Source File: HMacWithSha256.java    License: MIT License 5 votes vote down vote up
public static byte[] hmac(byte[] data, byte[] macKey) {
    HMac mac = new HMac(new SHA256Digest());
    mac.init(new KeyParameter(macKey));
    mac.update(data, 0, data.length);
    byte[] macOutput = new byte[mac.getMacSize()];
    mac.doFinal(macOutput, 0);
    return macOutput;
}
 
Example 27
Source Project: nuls-v2   Source File: ECKey.java    License: MIT License 5 votes vote down vote up
/**
 * 用私钥对数据进行签名
 *
 * @param input                需签名数据
 * @param privateKeyForSigning 私钥
 * @return byte[] 签名
 */
protected byte[] doSign(byte[] input, BigInteger privateKeyForSigning) {
    HexUtil.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 28
Source Project: symbol-sdk-java   Source File: Hashes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Hasher used for shared keys
 *
 * @param sharedSecret the shared secret
 * @return the shared key hash.
 */
public static byte[] sha256ForSharedKey(byte[] sharedSecret) {
    Digest hash = new SHA256Digest();
    byte[] info = "catapult".getBytes();
    int length = 32;
    byte[] sharedKey = new byte[length];
    HKDFParameters params = new HKDFParameters(sharedSecret, null, info);
    HKDFBytesGenerator hkdf = new HKDFBytesGenerator(hash);
    hkdf.init(params);
    hkdf.generateBytes(sharedKey, 0, length);
    return sharedKey;
}
 
Example 29
Source Project: ts3j   Source File: Ts3Crypt.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean verifySignature(ECPoint publicKey, byte[] data, byte[] signature) {
    DSADigestSigner signer = new DSADigestSigner(new ECDSASigner(), new SHA256Digest());
    ECPublicKeyParameters signingKey = new ECPublicKeyParameters(publicKey, getDomainParameters());

    signer.init(false, signingKey);
    signer.update(data, 0, data.length);

    return signer.verifySignature(signature);
}
 
Example 30
Source Project: ts3j   Source File: Ts3Crypt.java    License: Apache License 2.0 5 votes vote down vote up
public static byte[] createSignature(BigInteger privateKey, byte[] data) {
    DSADigestSigner signer = new DSADigestSigner(new ECDSASigner(), new SHA256Digest());
    ECPrivateKeyParameters signingKey = new ECPrivateKeyParameters(privateKey, getDomainParameters());

    signer.init(true, signingKey);
    signer.update(data, 0, data.length);

    return signer.generateSignature();
}