org.bouncycastle.crypto.Digest Java Examples

The following examples show how to use org.bouncycastle.crypto.Digest. 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: Sha3Hash.java    From nuls-v2 with MIT License 6 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 #2
Source File: PBKDF2CipherProvider.java    From localization_nifi with 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 File: HmacSignUtil.java    From littleca with 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 #4
Source File: P12ContentSignerBuilder.java    From xipki with 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 #5
Source File: PBKDF2CipherProvider.java    From nifi with 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 #6
Source File: Sha3Hash.java    From nuls-v2 with MIT License 6 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 #7
Source File: FileStreamWriter.java    From InflatableDonkey with 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 #8
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private Digest getHashDigest() {
    if ("SHA3".equals(hashAlgorithm)) {
        return new SHA3Digest();
    } else {
        // Default to SHA2
        return new SHA256Digest();
    }
}
 
Example #9
Source File: RFC6637Factory.java    From InflatableDonkey with 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 #10
Source File: Endpoint.java    From fabric-sdk-java with 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 #11
Source File: DIGEST.java    From warp10-platform with 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 #12
Source File: RFC5869KDF.java    From InflatableDonkey with 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 #13
Source File: KeySet.java    From InflatableDonkey with 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 #14
Source File: DiskChunkStore.java    From InflatableDonkey with 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 #15
Source File: NISTKDF.java    From InflatableDonkey with 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 #16
Source File: SRPAssistant.java    From InflatableDonkey with 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 #17
Source File: P12ContentSignerBuilder.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected Signer createSigner(AlgorithmIdentifier sigAlgId, AlgorithmIdentifier digAlgId)
    throws OperatorCreationException {
  if (!AlgorithmUtil.isDSASigAlg(sigAlgId)) {
    throw new OperatorCreationException("the given algorithm is not a valid DSA signature "
        + "algirthm '" + sigAlgId.getAlgorithm().getId() + "'");
  }

  Digest dig = digestProvider.get(digAlgId);
  DSASigner dsaSigner = new DSASigner();
  return plain ? new DSAPlainDigestSigner(dsaSigner, dig) : new DSADigestSigner(dsaSigner, dig);
}
 
Example #18
Source File: SignatureAssistant.java    From InflatableDonkey with MIT License 5 votes vote down vote up
static Optional<Digest> digest(Signature signature) {
    switch (signature.type()) {
        case 0x01:
            return Optional.ofNullable(new SHA256Digest());
        case 0x02:
            return Optional.ofNullable(new SHA512Digest());
        default:
            logger.warn("-- digest() - unsupported signature type: {}", signature);
            return Optional.empty();
    }
}
 
Example #19
Source File: SHATest.java    From java_security with MIT License 5 votes vote down vote up
public static void bcSHA1()
{
	
	Digest digest = new SHA1Digest();
	digest.update(src.getBytes(), 0, src.getBytes().length );
	byte[] sha1Bytes = new byte[digest.getDigestSize()];
	digest.doFinal(sha1Bytes, 0);
	System.out.println("bc sha-1:" + org.bouncycastle.util.encoders.Hex.toHexString(sha1Bytes));		
}
 
Example #20
Source File: HMac.java    From google-authenticator with Apache License 2.0 5 votes vote down vote up
private HMac(
    Digest digest,
    int    byteLength)
{
    this.digest = digest;
    digestSize = digest.getDigestSize();

    this.blockLength = byteLength;

    inputPad = new byte[blockLength];
    outputPad = new byte[blockLength];
}
 
Example #21
Source File: HashCalculator.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static ConcurrentBag<ConcurrentBagEntry<Digest>> getMessageDigests(HashAlgo hashAlgo) {
  ConcurrentBag<ConcurrentBagEntry<Digest>> mds = new ConcurrentBag<>();
  for (int i = 0; i < PARALLELISM; i++) {
    mds.add(new ConcurrentBagEntry<Digest>(hashAlgo.createDigest()));
  }
  return mds;
}
 
Example #22
Source File: HashCalculator.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static byte[] hash(HashAlgo hashAlgo, byte[]... datas) {
  Args.notNull(hashAlgo, "hashAlgo");
  Args.notNull(datas, "datas");

  if (!MDS_MAP.containsKey(hashAlgo)) {
    throw new IllegalArgumentException("unknown hash algo " + hashAlgo);
  }

  ConcurrentBag<ConcurrentBagEntry<Digest>> mds = MDS_MAP.get(hashAlgo);

  ConcurrentBagEntry<Digest> md0 = null;
  for (int i = 0; i < 3; i++) {
    try {
      md0 = mds.borrow(10, TimeUnit.SECONDS);
      break;
    } catch (InterruptedException ex) { // CHECKSTYLE:SKIP
    }
  }

  if (md0 == null) {
    throw new RuntimeOperatorException("could not get idle MessageDigest");
  }

  try {
    Digest md = md0.value();
    md.reset();
    for (byte[] data : datas) {
      if (data != null && data.length > 0) {
        md.update(data, 0, data.length);
      }
    }
    byte[] bytes = new byte[md.getDigestSize()];
    md.doFinal(bytes, 0);
    return bytes;
  } finally {
    mds.requite(md0);
  }
}
 
Example #23
Source File: HashCalculator.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static byte[] hash(HashAlgo hashAlgo, byte[] data, int offset, int len) {
  Args.notNull(hashAlgo, "hashAlgo");
  Args.notNull(data, "data");

  if (data.length - offset < len) {
    throw new IndexOutOfBoundsException("data.length - offset < len");
  }

  if (!MDS_MAP.containsKey(hashAlgo)) {
    throw new IllegalArgumentException("unknown hash algo " + hashAlgo);
  }

  ConcurrentBag<ConcurrentBagEntry<Digest>> mds = MDS_MAP.get(hashAlgo);

  ConcurrentBagEntry<Digest> md0 = null;
  for (int i = 0; i < 3; i++) {
    try {
      md0 = mds.borrow(10, TimeUnit.SECONDS);
      break;
    } catch (InterruptedException ex) { // CHECKSTYLE:SKIP
    }
  }

  if (md0 == null) {
    throw new RuntimeOperatorException("could not get idle MessageDigest");
  }

  try {
    Digest md = md0.value();
    md.reset();
    md.update(data, offset, len);
    byte[] bytes = new byte[md.getDigestSize()];
    md.doFinal(bytes, 0);
    return bytes;
  } finally {
    mds.requite(md0);
  }
}
 
Example #24
Source File: SignerUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static PSSSigner createPSSRSASigner(AlgorithmIdentifier sigAlgId,
    AsymmetricBlockCipher cipher) throws XiSecurityException {
  Args.notNull(sigAlgId, "sigAlgId");
  if (!PKCSObjectIdentifiers.id_RSASSA_PSS.equals(sigAlgId.getAlgorithm())) {
    throw new XiSecurityException("signature algorithm " + sigAlgId.getAlgorithm()
      + " is not allowed");
  }

  AlgorithmIdentifier digAlgId;
  try {
    digAlgId = AlgorithmUtil.extractDigesetAlgFromSigAlg(sigAlgId);
  } catch (NoSuchAlgorithmException ex) {
    throw new XiSecurityException(ex.getMessage(), ex);
  }

  RSASSAPSSparams param = RSASSAPSSparams.getInstance(sigAlgId.getParameters());

  AlgorithmIdentifier mfgDigAlgId = AlgorithmIdentifier.getInstance(
      param.getMaskGenAlgorithm().getParameters());

  Digest dig = getDigest(digAlgId);
  Digest mfgDig = getDigest(mfgDigAlgId);

  int saltSize = param.getSaltLength().intValue();
  int trailerField = param.getTrailerField().intValue();
  AsymmetricBlockCipher tmpCipher = (cipher == null) ? new RSABlindedEngine() : cipher;

  return new PSSSigner(tmpCipher, dig, mfgDig, saltSize, getTrailer(trailerField));
}
 
Example #25
Source File: SignerUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static Digest getDigest(AlgorithmIdentifier hashAlgo) throws XiSecurityException {
  HashAlgo hat = HashAlgo.getInstance(hashAlgo.getAlgorithm());
  if (hat != null) {
    return hat.createDigest();
  } else {
    throw new XiSecurityException("could not get digest for " + hashAlgo.getAlgorithm().getId());
  }
}
 
Example #26
Source File: SRPClient.java    From InflatableDonkey with 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));
}
 
Example #27
Source File: SRPAssistant.java    From InflatableDonkey with 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 #28
Source File: GMUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static void addUserId(Digest digest, byte[] userId) {
  int len = userId.length * 8;
  if (len > 0xFFFF) {
    throw new IllegalArgumentException("userId too long");
  }

  digest.update((byte)(len >> 8 & 0xFF));
  digest.update((byte)(len & 0xFF));
  digest.update(userId, 0, userId.length);
}
 
Example #29
Source File: SRPAssistant.java    From InflatableDonkey with 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 #30
Source File: RFC6637KDF.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public RFC6637KDF(
        Supplier<Digest> digestFactory,
        byte[] formattedOid,
        byte publicKeyAlgID,
        byte symAlgID,
        byte kdfHashID) {

    this.digestFactory = Objects.requireNonNull(digestFactory);
    this.formattedOid = Arrays.copyOf(formattedOid, formattedOid.length);
    this.publicKeyAlgID = publicKeyAlgID;
    this.symAlgID = symAlgID;
    this.kdfHashID = kdfHashID;
}