Java Code Examples for org.bouncycastle.crypto.Digest

The following examples show how to use org.bouncycastle.crypto.Digest. 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
Source Project: littleca   Source File: HmacSignUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static Mac getHmac(Digest digest, byte[] key) {
    KeyParameter keyParameter = new KeyParameter(key);
    HMac hmac = new HMac(new SM3Digest());
    hmac.init(keyParameter);

    return new Mac() {
        @Override
        public byte[] doFinal(byte[] bytes) {
            hmac.update(bytes, 0, bytes.length);
            byte[] result = new byte[hmac.getMacSize()];
            hmac.doFinal(result, 0);
            return result;
        }
    };

}
 
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: 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 4
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 5
Source Project: warp10-platform   Source File: DIGEST.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  Object o = stack.pop();

  if (!(o instanceof byte[])) {
    throw new WarpScriptException(getName() + " operates on a byte array.");
  }

  byte[] bytes = (byte[]) o;

  try {
    Digest digest = (Digest) digestAlgo.newInstance();

    byte[] digestOctets = new byte[digest.getDigestSize()];

    digest.update(bytes, 0, bytes.length);

    digest.doFinal(digestOctets, 0);

    stack.push(digestOctets);

    return stack;
  } catch (Exception exp) {
    throw new WarpScriptException(getName() + " unable to instantiate message digest.", exp);
  }
}
 
Example 6
Source Project: InflatableDonkey   Source File: KeySet.java    License: MIT License 6 votes vote down vote up
byte[] calculateChecksum() {
    try {
        // Re-encode the data minus the supplied checksum then calculate SHA256 hash.
        // This should ideally match the supplied checksum.
        // Verifies data integrity AND our decode/ encode processes.
        byte[] contents = toASN1Primitive(false).getEncoded();

        Digest digest = DIGEST.get();
        byte[] calculatedChecksum = new byte[digest.getDigestSize()];
        digest.update(contents, 0, contents.length);
        digest.doFinal(calculatedChecksum, 0);

        return calculatedChecksum;

    } catch (IOException ex) {
        throw new IllegalArgumentException(ex);
    }
}
 
Example 7
Source Project: InflatableDonkey   Source File: DiskChunkStore.java    License: MIT License 6 votes vote down vote up
DiskChunkStore(Object lock, Supplier<Digest> digests, BiPredicate<byte[], byte[]> testDigest,
        Path chunkFolder, Path tempFolder) throws IOException {
    if (!DirectoryAssistant.create(chunkFolder)) {
        throw new IOException("DiskChunkStore failed to create chunk folder: "
                + chunkFolder.normalize().toAbsolutePath());
    }
    if (!DirectoryAssistant.create(tempFolder)) {
        throw new IOException("DiskChunkStore failed to create temp folder: "
                + tempFolder.normalize().toAbsolutePath());
    }
    this.lock = Objects.requireNonNull(lock);
    this.digests = Objects.requireNonNull(digests);
    this.testDigest = Objects.requireNonNull(testDigest);
    this.chunkFolder = chunkFolder.normalize().toAbsolutePath();
    this.tempFolder = tempFolder.normalize().toAbsolutePath();
}
 
Example 8
Source Project: InflatableDonkey   Source File: NISTKDF.java    License: MIT License 6 votes vote down vote up
public static byte[]
        ctrHMac(byte[] keyDerivationKey, byte[] label, Supplier<Digest> digestSupplier, int keyLengthBytes) {

    logger.trace("<< ctrHMac() - keyDerivationKey: 0x{} label: {} digestSupplier: {} length: {}",
            Hex.toHexString(keyDerivationKey), Hex.toHexString(label), digestSupplier, keyLengthBytes);

    byte[] derivedKey = new byte[keyLengthBytes];

    // fixedInputData = label || 0x00 || dkLen in bits as 4 bytes big endian
    ByteBuffer buffer = ByteBuffer.allocate(label.length + 5);
    buffer.put(label);
    buffer.put((byte) 0);
    buffer.putInt(keyLengthBytes * 8);
    byte[] fixedInputData = buffer.array();
    logger.debug("-- ctrHMac() - fixed input data: 0x{}", Hex.toHexString(fixedInputData));

    HMac hMac = new HMac(digestSupplier.get());
    KDFCounterBytesGenerator generator = new KDFCounterBytesGenerator(hMac);
    generator.init(new KDFCounterParameters(keyDerivationKey, fixedInputData, R));
    generator.generateBytes(derivedKey, 0, derivedKey.length);

    logger.trace(">> ctrHMac() - derivedKey: 0x{}", Hex.toHexString(derivedKey));
    return derivedKey;
}
 
Example 9
Source Project: InflatableDonkey   Source File: SRPAssistant.java    License: MIT License 6 votes vote down vote up
public static byte[] generateM1(
        Digest digest,
        BigInteger N,
        BigInteger g,
        byte[] ephemeralKeyA,
        byte[] ephemeralKeyB,
        byte[] key,
        byte[] salt, // s
        byte[] identity) {

    // M1 = H(H(N) XOR H(g) | H(I) | s | A | B | K) 
    int length = length(N);

    // hI = H(I)
    byte[] hI = hash(digest, identity);

    // tmp = H(N) XOR H(g)
    byte[] hNxhG = ByteUtils.xor(hash(digest, padded(N, length)), hash(digest, padded(g, length)));

    return hash(digest, hNxhG, hI, salt, ephemeralKeyA, ephemeralKeyB, key);
}
 
Example 10
Source Project: InflatableDonkey   Source File: RFC5869KDF.java    License: MIT License 6 votes vote down vote up
public static final byte[]
        apply(byte[] ikm, byte[] salt, byte[] info, Supplier<Digest> digestSupplier, int keyLengthBytes) {
            
    logger.trace("<< apply() - ikm: 0x{} salt: 0x{} info: 0x{} digestSupplier: {} keyLengthBytes: {}",
            Hex.toHexString(ikm), Hex.toHexString(salt), Hex.toHexString(info), digestSupplier, keyLengthBytes);

    Digest hash = digestSupplier.get();
    byte[] okm = new byte[keyLengthBytes];

    HKDFParameters params = new HKDFParameters(ikm, salt, info);
    HKDFBytesGenerator hkdf = new HKDFBytesGenerator(hash);
    hkdf.init(params);
    hkdf.generateBytes(okm, 0, keyLengthBytes);

    logger.trace(">> apply() - output keying material: 0x{}", Hex.toHexString(okm));
    return okm;
}
 
Example 11
Source Project: InflatableDonkey   Source File: RFC6637Factory.java    License: MIT License 6 votes vote down vote up
private static RFC6637 create(
        String curveName,
        Supplier<Digest> digestFactory,
        Supplier<Wrapper> wrapperFactory,
        int publicKeyAlgID,
        int symAlgID,
        int symAlgIDLength,
        int kdfHashID) {

    try {
        ASN1ObjectIdentifier oid = ECNamedCurveTable.getOID(curveName);

        RFC6637KDF kdf = new RFC6637KDF(
                digestFactory,
                oid,
                (byte) publicKeyAlgID,
                (byte) symAlgID,
                (byte) kdfHashID);

        return new RFC6637(wrapperFactory, curveName, symAlgIDLength, kdf);

    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 12
Source Project: InflatableDonkey   Source File: FileStreamWriter.java    License: MIT License 6 votes vote down vote up
public static boolean copy(InputStream in,
        OutputStream out,
        Optional<XFileKey> keyCipher,
        Optional<byte[]> signature,
        Optional<IOFunction<InputStream, InputStream>> decompress) throws IOException {

    Digest digest = signature.flatMap(FileSignature::type)
            .orElse(FileSignature.ONE)
            .newDigest();

    DigestInputStream dis = new DigestInputStream(in, digest);

    InputStream fis = decryptStream(dis, keyCipher);

    if (decompress.isPresent()) {
        logger.info("-- copy() - decompressing");
        fis = decompress.get().apply(fis);
    }

    IOUtils.copyLarge(fis, out, new byte[BUFFER_SIZE]);
    out.flush();

    return testSignature(dis.getDigest(), signature);
}
 
Example 13
Source Project: xipki   Source File: P12ContentSignerBuilder.java    License: Apache License 2.0 6 votes vote down vote up
protected Signer createSigner(AlgorithmIdentifier sigAlgId, AlgorithmIdentifier digAlgId)
    throws OperatorCreationException {
  if (!AlgorithmUtil.isRSASigAlgId(sigAlgId)) {
    throw new OperatorCreationException("the given algorithm is not a valid RSA signature "
        + "algirthm '" + sigAlgId.getAlgorithm().getId() + "'");
  }

  if (!PKCSObjectIdentifiers.id_RSASSA_PSS.equals(sigAlgId.getAlgorithm())) {
    Digest dig = digestProvider.get(digAlgId);
    return new RSADigestSigner(dig);
  }

  try {
    return SignerUtil.createPSSRSASigner(sigAlgId);
  } catch (XiSecurityException ex) {
    throw new OperatorCreationException(ex.getMessage(), ex);
  }
}
 
Example 14
Source Project: netty-4.1.22   Source File: Digester.java    License: Apache License 2.0 5 votes vote down vote up
public static DigestCalculator sha1() {
    Digest digest = new SHA1Digest();
    AlgorithmIdentifier algId = new AlgorithmIdentifier(
            OIWObjectIdentifiers.idSHA1);

    return new Digester(digest, algId);
}
 
Example 15
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 16
Source Project: xipki   Source File: ResponseCacher.java    License: Apache License 2.0 5 votes vote down vote up
private long deriveId(int issuerId, byte[] identBytes) {
  ConcurrentBagEntry<Digest> digest0 = null;
  try {
    digest0 = idDigesters.borrow(2, TimeUnit.SECONDS);
  } catch (InterruptedException ex) {
    // do nothing
  }

  boolean newDigest = (digest0 == null);
  if (newDigest) {
    digest0 = new ConcurrentBagEntry<Digest>(HashAlgo.SHA1.createDigest());
  }

  byte[] hash = new byte[20];
  try {
    Digest digest = digest0.value();
    digest.reset();
    digest.update(int2Bytes(issuerId), 0, 2);
    digest.update(identBytes, 0, identBytes.length);
    digest.doFinal(hash, 0);
  } finally {
    if (newDigest) {
      idDigesters.add(digest0);
    } else {
      idDigesters.requite(digest0);
    }
  }

  return (0x7FL & hash[0]) << 56 // ignore the first bit
      | (0xFFL & hash[1]) << 48
      | (0xFFL & hash[2]) << 40
      | (0xFFL & hash[3]) << 32
      | (0xFFL & hash[4]) << 24
      | (0xFFL & hash[5]) << 16
      | (0xFFL & hash[6]) << 8
      | (0xFFL & hash[7]);
}
 
Example 17
Source Project: paseto   Source File: BouncyCastleV1CryptoProvider.java    License: MIT License 5 votes vote down vote up
@Override
public byte[] hmacSha384(byte[] m, byte[] key) {
	validateHmacSha384(m, key);

	Digest digest = new SHA384Digest();
	HMac hmac = new HMac(digest);

	hmac.init(new KeyParameter(key));
	byte[] out = new byte[hmac.getMacSize()];
	hmac.update(m, 0, m.length);
	hmac.doFinal(out, 0);
	return out;
}
 
Example 18
Source Project: nuls-v2   Source File: HashUtil.java    License: MIT License 5 votes vote down vote up
/**
 * @param data - message to hash
 * @return - reipmd160 hash of the message
 */
public static byte[] ripemd160(byte[] data) {
    Digest digest = new RIPEMD160Digest();
    if (data != null) {
        byte[] resBuf = new byte[digest.getDigestSize()];
        digest.update(data, 0, data.length);
        digest.doFinal(resBuf, 0);
        return resBuf;
    }
    throw new NullPointerException("Can't hash a NULL value");
}
 
Example 19
Source Project: xipki   Source File: ResponseCacher.java    License: Apache License 2.0 5 votes vote down vote up
public ResponseCacher(DataSourceWrapper datasource, boolean master, Validity validity) {
  this.datasource = Args.notNull(datasource, "datasource");
  this.master = master;
  this.validity = (int) (Args.notNull(validity, "validity").approxMinutes() * 60);
  this.sqlSelectIssuerCert = datasource.buildSelectFirstSql(1, "CERT FROM ISSUER WHERE ID=?");
  this.sqlSelectOcsp = datasource.buildSelectFirstSql(1,
      "IID,IDENT,GENERATED_AT,NEXT_UPDATE,RESP FROM OCSP WHERE ID=?");
  this.onService = new AtomicBoolean(false);

  this.idDigesters = new ConcurrentBag<>();
  for (int i = 0; i < 20; i++) {
    Digest md = HashAlgo.SHA1.createDigest();
    idDigesters.add(new ConcurrentBagEntry<Digest>(md));
  }
}
 
Example 20
Source Project: nuls-v2   Source File: Sha512Hash.java    License: MIT License 5 votes vote down vote up
public static byte[] sha512(byte[] bytes) {
    Digest digest = new SHA512Digest();
    digest.update(bytes, 0, bytes.length);
    byte[] rsData = new byte[digest.getDigestSize()];
    digest.doFinal(rsData, 0);
    return rsData;
}
 
Example 21
Source Project: nuls-v2   Source File: Sha3Hash.java    License: MIT License 5 votes vote down vote up
public static String sha3(byte[] bytes, int bitLength) {
    Digest digest = new SHA3Digest(bitLength);
    digest.update(bytes, 0, bytes.length);
    byte[] rsData = new byte[digest.getDigestSize()];
    digest.doFinal(rsData, 0);
    return HexUtil.encode(rsData);
}
 
Example 22
Source Project: nuls-v2   Source File: Sha3Hash.java    License: MIT License 5 votes vote down vote up
public static byte[] sha3bytes(byte[] bytes, int bitLength) {
    Digest digest = new SHA3Digest(bitLength);
    digest.update(bytes, 0, bytes.length);
    byte[] rsData = new byte[digest.getDigestSize()];
    digest.doFinal(rsData, 0);
    return rsData;
}
 
Example 23
Source Project: nuls-v2   Source File: KeccakHash.java    License: MIT License 5 votes vote down vote up
public static String keccak(byte[] bytes, int bitLength) {
    Digest digest = new KeccakDigest(bitLength);
    digest.update(bytes, 0, bytes.length);
    byte[] rsData = new byte[digest.getDigestSize()];
    digest.doFinal(rsData, 0);
    return HexUtil.encode(rsData);
}
 
Example 24
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 25
Source Project: WavesJ   Source File: Hash.java    License: MIT License 5 votes vote down vote up
private static byte[] hash(byte[] message, int ofs, int len, ThreadLocal<Digest> alg) {
    final Digest digest = digest(alg);
    final byte[] result = new byte[digest.getDigestSize()];
    digest.update(message, ofs, len);
    digest.doFinal(result, 0);
    return result;
}
 
Example 26
Source Project: fabric-sdk-java   Source File: CryptoPrimitives.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] hash(byte[] input) {
    Digest digest = getHashDigest();
    byte[] retValue = new byte[digest.getDigestSize()];
    digest.update(input, 0, input.length);
    digest.doFinal(retValue, 0);
    return retValue;
}
 
Example 27
Source Project: fabric-sdk-java   Source File: CryptoPrimitives.java    License: Apache License 2.0 5 votes vote down vote up
private Digest getHashDigest() {
    if ("SHA3".equals(hashAlgorithm)) {
        return new SHA3Digest();
    } else {
        // Default to SHA2
        return new SHA256Digest();
    }
}
 
Example 28
Source Project: InflatableDonkey   Source File: SRPAssistant.java    License: MIT License 5 votes vote down vote up
public static BigInteger generateS(
        Digest digest,
        BigInteger N,
        BigInteger g,
        BigInteger a,
        BigInteger k,
        BigInteger u,
        BigInteger x,
        BigInteger B) {

    // S = (B - k*(g^x)) ^ (a + ux)
    BigInteger exp = u.multiply(x).add(a);
    BigInteger tmp = g.modPow(x, N).multiply(k).mod(N);
    return B.subtract(tmp).mod(N).modPow(exp, N);
}
 
Example 29
Source Project: InflatableDonkey   Source File: SRPAssistant.java    License: MIT License 5 votes vote down vote up
static byte[] hash(Digest digest, byte[]... bytes) {
    for (byte[] b : bytes) {
        digest.update(b, 0, b.length);
    }

    byte[] output = new byte[digest.getDigestSize()];
    digest.doFinal(output, 0);
    return output;
}
 
Example 30
Source Project: InflatableDonkey   Source File: SRPClient.java    License: MIT License 5 votes vote down vote up
public SRPClient(SecureRandom random, Digest digest, BigInteger N, BigInteger g) {
    this.random = Objects.requireNonNull(random, "random");
    this.digest = Objects.requireNonNull(digest, "digest");
    this.N = Objects.requireNonNull(N, "N");
    this.g = Objects.requireNonNull(g, "g");

    logger.debug(" **SRP() - N: 0x{}", N.toString(16));
    logger.debug(" **SRP() - g: 0x{}", g.toString(16));
}