org.bouncycastle.crypto.digests.SHA1Digest Java Examples

The following examples show how to use org.bouncycastle.crypto.digests.SHA1Digest. 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: 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 #2
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 #3
Source File: ECUtil.java    From ECTester with MIT License 6 votes vote down vote up
private static byte[] hashCurve(EC_Curve curve) {
    int bytes = (curve.getBits() + 7) / 8;
    byte[] result = new byte[bytes];
    SHA1Digest digest = new SHA1Digest();
    byte[] curveName = curve.getId().getBytes(StandardCharsets.US_ASCII);
    digest.update(curveName, 0, curveName.length);
    int written = 0;
    while (written < bytes) {
        byte[] dig = new byte[digest.getDigestSize()];
        digest.doFinal(dig, 0);
        int toWrite = digest.getDigestSize() > bytes - written ? bytes - written : digest.getDigestSize();
        System.arraycopy(dig, 0, result, written, toWrite);
        written += toWrite;
        digest.update(dig, 0, dig.length);
    }
    return result;
}
 
Example #4
Source File: SnapshotDirectory.java    From LiquidDonkey with MIT License 6 votes vote down vote up
static SnapshotDirectory from(
        Path base,
        String udidStr,
        String snapshotIdStr,
        boolean isFlat,
        boolean isCombined,
        String combinedDirectory) {

    SHA1Digest sha1 = new SHA1Digest();

    Path folder = isCombined
            ? base.resolve(udidStr).resolve(combinedDirectory)
            : base.resolve(udidStr).resolve(snapshotIdStr);

    return isFlat
            ? new FlatSnapshotDirectory(folder, sha1)
            : new NonFlatSnapshotDirectory(folder, sha1);
}
 
Example #5
Source File: TOTPMIDletTest.java    From totp-me with Apache License 2.0 5 votes vote down vote up
public void testTOTP() {
	HMac sha1Hmac = new HMac(new SHA1Digest());
	sha1Hmac.init(new KeyParameter(seed20));
	HMac sha256Hmac = new HMac(new SHA256Digest());
	sha256Hmac.init(new KeyParameter(seed32));
	HMac sha512Hmac = new HMac(new SHA512Digest());
	sha512Hmac.init(new KeyParameter(seed64));
	for (int i = 0; i < TEST_TIME.length; i++) {
		long counter = TOTPMIDlet.getCounter(TEST_TIME[i], TIMESTEP);
		assertEquals(SHA1_VALUES[i], TOTPMIDlet.genToken(counter, sha1Hmac, DIGITS));
		assertEquals(SHA256_VALUES[i], TOTPMIDlet.genToken(counter, sha256Hmac, DIGITS));
		assertEquals(SHA512_VALUES[i], TOTPMIDlet.genToken(counter, sha512Hmac, DIGITS));
	}
}
 
Example #6
Source File: Digester.java    From netty-4.1.22 with 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 #7
Source File: TransactionId.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static TransactionId sha1TransactionId(byte[] content) {
  Args.notNull(content, "content");

  SHA1Digest dgst = new SHA1Digest();
  dgst.update(content, 0, content.length);
  byte[] digest = new byte[20];
  dgst.doFinal(digest, 0);
  return new TransactionId(digest);
}
 
Example #8
Source File: CheckCodeScreen.java    From google-authenticator with Apache License 2.0 5 votes vote down vote up
static String getCheckCode(String secret)
    throws Base32String.DecodingException {
  final byte[] keyBytes = Base32String.decode(secret);
  Mac mac = new HMac(new SHA1Digest());
  mac.init(new KeyParameter(keyBytes));
  PasscodeGenerator pcg = new PasscodeGenerator(mac);
  return pcg.generateResponseCode(0L);
}
 
Example #9
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 #10
Source File: Hash.java    From balzac with Apache License 2.0 5 votes vote down vote up
public static Hash sha1(byte[] bytes) {
    SHA1Digest digest = new SHA1Digest();
    digest.update(bytes, 0, bytes.length);
    byte[] sha1Hash = new byte[20];
    digest.doFinal(sha1Hash, 0);
    return new Hash(sha1Hash);
}
 
Example #11
Source File: CryptAeadBase.java    From shadowsocks-java with MIT License 5 votes vote down vote up
private byte[] genSubkey(byte[] salt) {
    HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA1Digest());
    hkdf.init(new HKDFParameters(_ssKey.getEncoded(), salt, info));
    byte[] okm = new byte[getKeyLength()];
    hkdf.generateBytes(okm, 0, getKeyLength());
    return okm;
}
 
Example #12
Source File: AESDecrypterBC.java    From fingen with Apache License 2.0 5 votes vote down vote up
public void init( String pwStr, int keySize, byte[] salt, byte[] pwVerification ) throws ZipException {
	byte[] pwBytes = pwStr.getBytes();
	
	super.saltBytes = salt;

	PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
	generator.init( pwBytes, salt, ITERATION_COUNT );

	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT*2 + 16);
	byte[] keyBytes = ((KeyParameter)cipherParameters).getKey();

	this.cryptoKeyBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, 0, cryptoKeyBytes, 0, KEY_SIZE_BYTE );

	this.authenticationCodeBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE, authenticationCodeBytes, 0, KEY_SIZE_BYTE );

	// based on SALT + PASSWORD (password is probably correct)
	this.pwVerificationBytes = new byte[ 2 ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE*2, this.pwVerificationBytes, 0, 2 );

	if( !ByteArrayHelper.isEqual( this.pwVerificationBytes, pwVerification ) ) {
		throw new ZipException("wrong password - " + ByteArrayHelper.toString(this.pwVerificationBytes) + "/ " + ByteArrayHelper.toString(pwVerification));
	}

	// create the first 16 bytes of the key sequence again (using pw+salt)
	generator.init( pwBytes, salt, ITERATION_COUNT );
	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT);

	// checksum added to the end of the encrypted data, update on each encryption call
	this.mac = new HMac( new SHA1Digest() );
	mac.init( new KeyParameter(authenticationCodeBytes) );

	this.aesCipher = new SICBlockCipher(new AESEngine());
	this.blockSize = aesCipher.getBlockSize();

	// incremented on each 16 byte block and used as encryption NONCE (ivBytes)
	nonce = 1;
}
 
Example #13
Source File: SecP256K1BlockCipher.java    From nem.core with MIT License 4 votes vote down vote up
private static IESEngine createIesEngine() {
	return new IESEngine(
			new ECDHBasicAgreement(),
			new KDF2BytesGenerator(new SHA1Digest()),
			new HMac(new SHA1Digest()));
}
 
Example #14
Source File: BouncyCastleHasher.java    From hash-bench with MIT License 4 votes vote down vote up
public static final void register(final Map<String, Hasher> hashers) {
  hashers.put(BouncyCastleHasher.GOST,
          new BouncyCastleHasher(new GOST3411Digest()));
  hashers.put(BouncyCastleHasher.MD2,
          new BouncyCastleHasher(new MD2Digest()));
  hashers.put(BouncyCastleHasher.MD4,
          new BouncyCastleHasher(new MD4Digest()));
  hashers.put(BouncyCastleHasher.MD5,
          new BouncyCastleHasher(new MD5Digest()));
  hashers.put(BouncyCastleHasher.RIPEMD128,
          new BouncyCastleHasher(new RIPEMD128Digest()));
  hashers.put(BouncyCastleHasher.RIPEMD160,
          new BouncyCastleHasher(new RIPEMD160Digest()));
  hashers.put(BouncyCastleHasher.RIPEMD256,
          new BouncyCastleHasher(new RIPEMD256Digest()));
  hashers.put(BouncyCastleHasher.RIPEMD320,
          new BouncyCastleHasher(new RIPEMD320Digest()));
  hashers.put(BouncyCastleHasher.SHA1,
          new BouncyCastleHasher(new SHA1Digest()));
  hashers.put(BouncyCastleHasher.SHA224,
          new BouncyCastleHasher(new SHA224Digest()));
  hashers.put(BouncyCastleHasher.SHA256,
          new BouncyCastleHasher(new SHA256Digest()));
  hashers.put(BouncyCastleHasher.SHA3,
          new BouncyCastleHasher(new SHA3Digest()));
  hashers.put(BouncyCastleHasher.SHA384,
          new BouncyCastleHasher(new SHA384Digest()));
  hashers.put(BouncyCastleHasher.SHA512,
          new BouncyCastleHasher(new SHA512Digest()));
  hashers.put(BouncyCastleHasher.SHA512_T,
          new BouncyCastleHasher(new SHA512tDigest(7 * 8)));
  hashers.put(BouncyCastleHasher.SKEIN1024, new BouncyCastleHasher(
          new SkeinDigest(SkeinDigest.SKEIN_1024, Long.BYTES * 8)));
  hashers.put(BouncyCastleHasher.SKEIN256, new BouncyCastleHasher(
          new SkeinDigest(SkeinDigest.SKEIN_256, Long.BYTES * 8)));
  hashers.put(BouncyCastleHasher.SKEIN512, new BouncyCastleHasher(
          new SkeinDigest(SkeinDigest.SKEIN_512, Long.BYTES * 8)));
  hashers.put(BouncyCastleHasher.SM3,
          new BouncyCastleHasher(new SM3Digest()));
  hashers.put(BouncyCastleHasher.TIGER,
          new BouncyCastleHasher(new TigerDigest()));
  hashers.put(BouncyCastleHasher.WHIRLPOOL2,
          new BouncyCastleHasher(new WhirlpoolDigest()));
}
 
Example #15
Source File: FileDigestA.java    From InflatableDonkey with MIT License 4 votes vote down vote up
public FileDigestA() {
    digest = new SHA1Digest();
    digest.update(SALT, 0, SALT.length);
}
 
Example #16
Source File: PBKDF2.java    From InflatableDonkey with MIT License 4 votes vote down vote up
public static byte[] generate(byte[] password, byte[] salt, int iterations, int lengthBits) {
    return generate(new SHA1Digest(), password, salt, iterations, lengthBits);
}
 
Example #17
Source File: SnapshotDirectory.java    From LiquidDonkey with MIT License 4 votes vote down vote up
NonFlatSnapshotDirectory(Path folder, SHA1Digest sha1) {
    super(folder, sha1);
}
 
Example #18
Source File: SnapshotDirectory.java    From LiquidDonkey with MIT License 4 votes vote down vote up
FlatSnapshotDirectory(Path folder, SHA1Digest sha1) {
    super(folder, sha1);
}
 
Example #19
Source File: FileDecrypter.java    From LiquidDonkey with MIT License 4 votes vote down vote up
/**
 * Returns a new instance.
 *
 * @return a new instance, not null
 */
public static FileDecrypter create() {
    return FileDecrypter.from(
            new BufferedBlockCipher(new CBCBlockCipher(new AESEngine())),
            new SHA1Digest());
}
 
Example #20
Source File: FileDecrypter.java    From LiquidDonkey with MIT License 4 votes vote down vote up
static FileDecrypter from(BufferedBlockCipher cbcAes, SHA1Digest sha1) {
    return new FileDecrypter(cbcAes, sha1);
}
 
Example #21
Source File: CrmfKeyWrapper.java    From xipki with Apache License 2.0 4 votes vote down vote up
/**
 * Encrypt the key with the following output.
 * <pre>
 * ECIES-Ciphertext-Value ::= SEQUENCE {
 *     ephemeralPublicKey ECPoint,
 *     symmetricCiphertext OCTET STRING,
 *     macTag OCTET STRING
 * }
 *
 * ECPoint ::= OCTET STRING
 * </pre>
 */
@Override
public byte[] generateWrappedKey(byte[] keyToWrap) throws OperatorException {
  try {
    BlockCipher cbcCipher = new CBCBlockCipher(new AESEngine());
    IESCipher cipher = new IESCipher(
        new IESEngine(new ECDHBasicAgreement(),
            new KDF2BytesGenerator(new SHA1Digest()),
            new HMac(new SHA1Digest()),
            new PaddedBufferedBlockCipher(cbcCipher)), 16);

    // According to the ยง3.8 in SEC 1, Version 2.0:
    // "Furthermore here the 16 octet or 128 bit IV for AES in CBC mode should always take
    //  the value 0000000000000000_{16}"
    byte[] iv = new byte[16];
    IESParameterSpec spec = new IESParameterSpec(null, null, aesKeySize, aesKeySize, iv);
    cipher.engineInit(Cipher.ENCRYPT_MODE, publicKey, spec, new SecureRandom());
    byte[] bcResult = cipher.engineDoFinal(keyToWrap, 0, keyToWrap.length);
    // convert the result to ASN.1 format
    ASN1Encodable[] array = new ASN1Encodable[3];
    // ephemeralPublicKey ECPoint
    byte[] ephemeralPublicKey = new byte[ephemeralPublicKeyLen];

    System.arraycopy(bcResult, 0, ephemeralPublicKey, 0, ephemeralPublicKeyLen);
    array[0] = new DEROctetString(ephemeralPublicKey);

    // symmetricCiphertext OCTET STRING
    int symmetricCiphertextLen = bcResult.length - ephemeralPublicKeyLen - macLen;
    byte[] symmetricCiphertext = new byte[symmetricCiphertextLen];
    System.arraycopy(bcResult, ephemeralPublicKeyLen,
        symmetricCiphertext, 0, symmetricCiphertextLen);
    array[1] = new DEROctetString(symmetricCiphertext);

    // macTag OCTET STRING
    byte[] macTag = new byte[macLen];
    System.arraycopy(bcResult, ephemeralPublicKeyLen + symmetricCiphertextLen,
        macTag, 0, macLen);
    array[2] = new DEROctetString(macTag);
    return new DERSequence(array).getEncoded();
  } catch (Exception ex) {
    throw new OperatorException("error while generateWrappedKey", ex);
  }
}
 
Example #22
Source File: AESEncrypterBC.java    From fingen with Apache License 2.0 4 votes vote down vote up
/**
 * Setup AES encryption based on pwBytes using WinZipAES approach
 * with SALT and pwVerification bytes based on password+salt.
 */
public void init( String pwStr, int keySize ) throws ZipException {
	byte[] pwBytes = pwStr.getBytes();
	PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
	this.saltBytes = createSalt();
	generator.init( pwBytes, saltBytes, ITERATION_COUNT );

	// create 2 byte[16] for two keys and one byte[2] for pwVerification
	// 1. encryption / 2. athentication (via HMAC/hash) /
	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT*2 + 16);
	byte[] keyBytes = ((KeyParameter)cipherParameters).getKey();

	this.cryptoKeyBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, 0, cryptoKeyBytes, 0, KEY_SIZE_BYTE );

	this.authenticationCodeBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE, authenticationCodeBytes, 0, KEY_SIZE_BYTE );

	// based on SALT + PASSWORD (password is probably correct)
	this.pwVerificationBytes = new byte[ 2 ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE*2, pwVerificationBytes, 0, 2 );

	// create the first 16 bytes of the key sequence again (using pw+salt)
	generator.init( pwBytes, saltBytes, ITERATION_COUNT );
	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT);

	// checksum added to the end of the encrypted data, update on each encryption call
	this.mac = new HMac( new SHA1Digest() );
	mac.init( new KeyParameter(authenticationCodeBytes) );

	this.aesCipher = new SICBlockCipher(new AESEngine());
	this.blockSize = aesCipher.getBlockSize();

	// incremented on each 16 byte block and used as encryption NONCE (ivBytes)
	nonce = 1;
	
	if( LOG.isLoggable(Level.FINEST) ) {
		LOG.finest( "pwBytes   = " + ByteArrayHelper.toString(pwBytes) + " - " + pwBytes.length );
		LOG.finest( "salt      = " + ByteArrayHelper.toString(saltBytes) + " - " + saltBytes.length );
		LOG.finest( "pwVerif   = " + ByteArrayHelper.toString(pwVerificationBytes) + " - " + pwVerificationBytes.length );
	}
}
 
Example #23
Source File: BCDigestRandomSource.java    From archistar-smc with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * create a new RandomSource using default params (SHA1-based)
 */
public BCDigestRandomSource() {
    this.digest = new SHA1Digest();
    this.drng = new DigestRandomGenerator(digest);
}