public static final Digest createHash(int hashAlgorithm) { switch (hashAlgorithm) { case HashAlgorithm.md5: return new MD5Digest(); case HashAlgorithm.sha1: return new SHA1Digest(); case HashAlgorithm.sha224: return new SHA224Digest(); case HashAlgorithm.sha256: return new SHA256Digest(); case HashAlgorithm.sha384: return new SHA384Digest(); case HashAlgorithm.sha512: return new SHA512Digest(); default: throw new IllegalArgumentException("unknown HashAlgorithm"); } }
public static final Digest cloneHash(int hashAlgorithm, Digest hash) { switch (hashAlgorithm) { case HashAlgorithm.md5: return new MD5Digest((MD5Digest)hash); case HashAlgorithm.sha1: return new SHA1Digest((SHA1Digest)hash); case HashAlgorithm.sha224: return new SHA224Digest((SHA224Digest)hash); case HashAlgorithm.sha256: return new SHA256Digest((SHA256Digest)hash); case HashAlgorithm.sha384: return new SHA384Digest((SHA384Digest)hash); case HashAlgorithm.sha512: return new SHA512Digest((SHA512Digest)hash); default: throw new IllegalArgumentException("unknown HashAlgorithm"); } }
protected Digest createHMACDigest(int macAlgorithm) throws IOException { switch (macAlgorithm) { case MACAlgorithm._null: return null; case MACAlgorithm.hmac_md5: return new MD5Digest(); case MACAlgorithm.hmac_sha1: return new SHA1Digest(); case MACAlgorithm.hmac_sha256: return new SHA256Digest(); case MACAlgorithm.hmac_sha384: return new SHA384Digest(); case MACAlgorithm.hmac_sha512: return new SHA512Digest(); default: throw new TlsFatalAlert(AlertDescription.internal_error); } }
private static BigInteger deriveSessionKey(BigInteger keyingMaterial) { /* * You should use a secure key derivation function (KDF) to derive the session key. * * For the purposes of this example, I'm just going to use a hash of the keying material. */ SHA256Digest digest = new SHA256Digest(); byte[] keyByteArray = keyingMaterial.toByteArray(); byte[] output = new byte[digest.getDigestSize()]; digest.update(keyByteArray, 0, keyByteArray.length); digest.doFinal(output, 0); return new BigInteger(output); }
public static Digest createHash(short hashAlgorithm) { switch (hashAlgorithm) { case HashAlgorithm.md5: return new MD5Digest(); case HashAlgorithm.sha1: return new SHA1Digest(); case HashAlgorithm.sha224: return new SHA224Digest(); case HashAlgorithm.sha256: return new SHA256Digest(); case HashAlgorithm.sha384: return new SHA384Digest(); case HashAlgorithm.sha512: return new SHA512Digest(); default: throw new IllegalArgumentException("unknown HashAlgorithm"); } }
public static Digest cloneHash(short hashAlgorithm, Digest hash) { switch (hashAlgorithm) { case HashAlgorithm.md5: return new MD5Digest((MD5Digest)hash); case HashAlgorithm.sha1: return new SHA1Digest((SHA1Digest)hash); case HashAlgorithm.sha224: return new SHA224Digest((SHA224Digest)hash); case HashAlgorithm.sha256: return new SHA256Digest((SHA256Digest)hash); case HashAlgorithm.sha384: return new SHA384Digest((SHA384Digest)hash); case HashAlgorithm.sha512: return new SHA512Digest((SHA512Digest)hash); default: throw new IllegalArgumentException("unknown HashAlgorithm"); } }
/** * which generates the p and g values from the given parameters, returning * the CramerShoupParameters object. * <p> * Note: can take a while... * </p> */ public CramerShoupParameters generateParameters() { // // find a safe prime p where p = 2*q + 1, where p and q are prime. // BigInteger[] safePrimes = ParametersHelper.generateSafePrimes(size, certainty, random); // BigInteger p = safePrimes[0]; BigInteger q = safePrimes[1]; BigInteger g1 = ParametersHelper.selectGenerator(q, random); BigInteger g2 = ParametersHelper.selectGenerator(q, random); while (g1.equals(g2)) { g2 = ParametersHelper.selectGenerator(q, random); } return new CramerShoupParameters(q, g1, g2, new SHA256Digest()); }
public void performTest() throws Exception { doExpectedTest(new SHA1Digest(), 0, expected0SHA1, noCycle0SHA1); doExpectedTest(new SHA256Digest(), 0, expected0SHA256, noCycle0SHA256); doExpectedTest(new SHA1Digest(), 100, expected100SHA1); doExpectedTest(new SHA256Digest(), 100, expected100SHA256); doExpectedTest(new SHA1Digest(), ZERO_SEED, expected0SHA1); doExpectedTest(new SHA256Digest(), ZERO_SEED, expected0SHA256); doExpectedTest(new SHA1Digest(), TEST_SEED, expectedTestSHA1); doExpectedTest(new SHA256Digest(), TEST_SEED, expectedTestSHA256); doCountTest(new SHA1Digest(), TEST_SEED, sha1Xors); doCountTest(new SHA256Digest(), TEST_SEED, sha256Xors); }
public void performTest() { checkMask(1, new MGF1BytesGenerator(new ShortenedDigest(new SHA256Digest(), 20)), seed1, mask1); checkMask(2, new MGF1BytesGenerator(new SHA1Digest()), seed2, mask2); checkMask(3, new MGF1BytesGenerator(new ShortenedDigest(new SHA256Digest(), 20)), seed3, mask3); try { new MGF1BytesGenerator(new SHA1Digest()).generateBytes(new byte[10], 0, 20); fail("short input array not caught"); } catch (DataLengthException e) { // expected } }
public void performTest() { checkMask(1, new KDF1BytesGenerator(new ShortenedDigest(new SHA256Digest(), 20)), seed1, mask1); checkMask(2, new KDF1BytesGenerator(new SHA1Digest()), seed2, mask2); checkMask(3, new KDF1BytesGenerator(new ShortenedDigest(new SHA256Digest(), 20)), seed3, mask3); try { new KDF1BytesGenerator(new SHA1Digest()).generateBytes(new byte[10], 0, 20); fail("short input array not caught"); } catch (DataLengthException e) { // expected } }
public void performTest() { checkMask(1, new KDF2BytesGenerator(new ShortenedDigest(new SHA256Digest(), 20)), seed1, mask1); checkMask(2, new KDF2BytesGenerator(new ShortenedDigest(new SHA256Digest(), 20)), seed2, mask2); checkMask(3, new KDF2BytesGenerator(new SHA256Digest()), seed2, adjustedMask2); checkMask(4, new KDF2BytesGenerator(new SHA1Digest()), seed2, sha1Mask); checkMask(5, new KDF2BytesGenerator(new SHA1Digest()), seed3, mask3); checkMask(6, new KDF2BytesGenerator(new SHA1Digest()), seed4, mask4); try { new KDF2BytesGenerator(new SHA1Digest()).generateBytes(new byte[10], 0, 20); fail("short input array not caught"); } catch (DataLengthException e) { // expected } }
@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]; } }
/** * A password-based data decryption using a constant salt value "<b>constantSalt</b>" * @param cipher * @param password * @param salt * @param iterationCount * @return * @throws Exception */ public static byte[] decrypt(byte[] cipher, String password) throws Exception { PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(new SHA256Digest()); char[] passwordChars = password.toCharArray(); final byte[] pkcs12PasswordBytes = PBEParametersGenerator.PKCS12PasswordToBytes(passwordChars); pGen.init(pkcs12PasswordBytes, constantSalt.getBytes(), iterations); CBCBlockCipher aesCBC = new CBCBlockCipher(new AESEngine()); ParametersWithIV aesCBCParams = (ParametersWithIV) pGen.generateDerivedParameters(256, 128); aesCBC.init(false, aesCBCParams); PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(aesCBC, new PKCS7Padding()); byte[] plainTemp = new byte[aesCipher.getOutputSize(cipher.length)]; int offset = aesCipher.processBytes(cipher, 0, cipher.length, plainTemp, 0); int last = aesCipher.doFinal(plainTemp, offset); final byte[] plain = new byte[offset + last]; System.arraycopy(plainTemp, 0, plain, 0, plain.length); return plain; }
public static int calculateRounds(int milliseconds) { Logging.info("Calculating how many SHA1 rounds we can do in %d millis.", milliseconds); HMac mac = new HMac(new SHA256Digest()); byte[] state = new byte[mac.getMacSize()]; long startTime = System.currentTimeMillis(); int pbkdf2Iterations = 0; while((System.currentTimeMillis() - startTime) < milliseconds) { mac.update(state, 0, state.length); mac.doFinal(state, 0); pbkdf2Iterations++; } pbkdf2Iterations = Math.max(pbkdf2Iterations, PBKDF2Descriptor.MINIMUM_PBKD2_ITERS); Logging.info("Got %d", pbkdf2Iterations); return pbkdf2Iterations; }
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; }
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); }
/** * Calculates the signature of a ticket and updates the given {@link Ticket} object directly. * * @throws IllegalStateException * If ticket cannot be signed. */ public void signTicket(Ticket ticket) throws IllegalStateException { byte[] serialized = TicketUtil.serialize(ticket); byte[] claimBytes = TicketUtil.deserialize(ByteBuffer.wrap(serialized)).getRight(); RSAPrivateCrtKeyParameters signingKey = keyManager.getPrivateSigningKey(); if (signingKey == null) throw new IllegalStateException("Cannot sign ticket because there is no private signing key available."); RSADigestSigner signer = new RSADigestSigner(new SHA256Digest()); signer.init(true, signingKey); signer.update(claimBytes, 0, claimBytes.length); try { byte[] signature = signer.generateSignature(); ticket.setSignature(signature); } catch (DataLengthException | CryptoException e) { throw new IllegalStateException("Cannot sign ticket", e); } }
private void internalSetUserPassword(SUser user, String newPassword) throws TException { BouncyCastleUtil.ensureInitialized(); byte[] newSalt = new byte[SALT_LENGTH_BYTES]; if (useStrongRandom) { try { SecureRandom.getInstanceStrong().nextBytes(newSalt); } catch (NoSuchAlgorithmException e) { logger.error("Internal error when calculating new salt for new password", e); throw new TException("Internal error.", e); } } else { // use non-string random. ThreadLocalRandom.current().nextBytes(newSalt); } PKCS5S2ParametersGenerator pbkdf2sha256 = new PKCS5S2ParametersGenerator(new SHA256Digest()); pbkdf2sha256.init(newPassword.getBytes(Charset.forName("UTF-8")), newSalt, PBKDF2_ITERATIONS); byte[] newHash = ((KeyParameter) pbkdf2sha256.generateDerivedParameters(HASH_LENGTH_BYTES * 8)).getKey(); user.setPassword(new SPassword()); user.getPassword().setHash(newHash); user.getPassword().setSalt(newSalt); }
@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; }
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); }
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); }
public static final Digest createHash(short hashAlgorithm) { switch (hashAlgorithm) { case HashAlgorithm.md5: return new MD5Digest(); case HashAlgorithm.sha1: return new SHA1Digest(); case HashAlgorithm.sha224: return new SHA224Digest(); case HashAlgorithm.sha256: return new SHA256Digest(); case HashAlgorithm.sha384: return new SHA384Digest(); case HashAlgorithm.sha512: return new SHA512Digest(); default: throw new IllegalArgumentException("unknown HashAlgorithm"); } }
public static final Digest cloneHash(short hashAlgorithm, Digest hash) { switch (hashAlgorithm) { case HashAlgorithm.md5: return new MD5Digest((MD5Digest)hash); case HashAlgorithm.sha1: return new SHA1Digest((SHA1Digest)hash); case HashAlgorithm.sha224: return new SHA224Digest((SHA224Digest)hash); case HashAlgorithm.sha256: return new SHA256Digest((SHA256Digest)hash); case HashAlgorithm.sha384: return new SHA384Digest((SHA384Digest)hash); case HashAlgorithm.sha512: return new SHA512Digest((SHA512Digest)hash); default: throw new IllegalArgumentException("unknown HashAlgorithm"); } }
private ECPoint generatePackPoint(SHA256Digest digest, byte[] ballot, byte[] hash) { BigInteger element; ECPoint point; do { digest.update(seed, 0, seed.length); for (int b = 0; b != ballot.length; b++) { digest.update(ballot[b]); } digest.doFinal(hash, 0); digest.update(hash, 0, hash.length); element = new BigInteger(1, hash).mod(domainParameters.getN()); point = domainParameters.getG().multiply(element).normalize(); } while (element.equals(BigInteger.ZERO) || packMap.containsKey(point)); return point; }
private BigInteger computeChallenge(ECPoint a, ECPoint b, ECPoint c, ECPoint partial, ECPoint g, ECPoint q) { SHA256Digest sha256 = new SHA256Digest(); addIn(sha256, a); addIn(sha256, b); addIn(sha256, c); addIn(sha256, partial); addIn(sha256, g); addIn(sha256, q); byte[] res = new byte[sha256.getDigestSize()]; sha256.doFinal(res, 0); return new BigInteger(1, res); }
private BigInteger computeChallenge(ECPoint a, ECPoint b, ECPoint c, ECPair partial, ECPoint g) { SHA256Digest sha256 = new SHA256Digest(); addIn(sha256, a); addIn(sha256, b); addIn(sha256, c); addIn(sha256, partial.getX()); addIn(sha256, g); addIn(sha256, q); byte[] res = new byte[sha256.getDigestSize()]; sha256.doFinal(res, 0); return new BigInteger(1, res); }
private byte[] doOperation(byte[] input, boolean isEncrypt) { AsymmetricBlockCipher cipher = new OAEPEncoding(new RSAEngine(), new SHA256Digest(), new SHA1Digest(), null); RSAKeyParameters key = isEncrypt ? publicKey : privateKey; cipher.init(isEncrypt, key); try { return cipher.processBlock(input, 0, input.length); } catch (InvalidCipherTextException e) { throw new EncryptionException("Encryption fails", e); } }