Example usage for org.bouncycastle.crypto.digests SHA256Digest SHA256Digest

List of usage examples for org.bouncycastle.crypto.digests SHA256Digest SHA256Digest

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.digests SHA256Digest SHA256Digest.

Prototype

public SHA256Digest() 

Source Link

Document

Standard constructor

Usage

From source file:org.cryptoworkshop.ximix.test.tests.ECDSAProcessingTest.java

License:Apache License

@Test
public void testECDSASigning() throws Exception {

    SquelchingThrowableHandler handler = new SquelchingThrowableHandler();

    ///*  w  ww  . ja  v  a 2 s. co  m*/
    // Squelch out socket exceptions emitted by close of connections below.
    //
    handler.squelchType(SocketException.class);

    XimixNode nodeOne = getXimixNode("/conf/mixnet.xml", "/conf/node1.xml", handler);
    NodeTestUtil.launch(nodeOne);

    XimixNode nodeTwo = getXimixNode("/conf/mixnet.xml", "/conf/node2.xml", handler);
    NodeTestUtil.launch(nodeTwo);

    XimixNode nodeThree = getXimixNode("/conf/mixnet.xml", "/conf/node3.xml", handler);
    NodeTestUtil.launch(nodeThree);

    XimixNode nodeFour = getXimixNode("/conf/mixnet.xml", "/conf/node4.xml", handler);
    NodeTestUtil.launch(nodeFour);

    XimixNode nodeFive = getXimixNode("/conf/mixnet.xml", "/conf/node5.xml", handler);
    NodeTestUtil.launch(nodeFive);

    XimixRegistrar registrar = XimixRegistrarFactory
            .createAdminServiceRegistrar(ResourceAnchor.load("/conf/mixnet.xml"), new TestNotifier());

    KeyGenerationService keyGenerationService = registrar.connect(KeyGenerationService.class);

    KeyGenerationOptions keyGenOptions = new KeyGenerationOptions.Builder(Algorithm.ECDSA, "secp256r1")
            .withThreshold(2).withNodes("A", "B", "C", "D").build();

    ECPublicKeyParameters sigPubKey = (ECPublicKeyParameters) PublicKeyFactory
            .createKey(keyGenerationService.generatePublicKey("ECKEY", keyGenOptions));

    SigningService signingService = registrar.connect(SigningService.class);

    SHA256Digest sha256 = new SHA256Digest();

    byte[] message = "hello world!".getBytes();
    byte[] hash = new byte[sha256.getDigestSize()];

    sha256.update(message, 0, message.length);

    sha256.doFinal(hash, 0);

    SignatureGenerationOptions sigGenOptions = new SignatureGenerationOptions.Builder(Algorithm.ECDSA)
            .withThreshold(2).withNodes("A", "B", "C", "D").build();

    byte[] dsaSig = signingService.generateSignature("ECKEY", sigGenOptions, hash);

    //
    // check the signature locally.
    //
    ECDSASigner signer = new ECDSASigner();

    signer.init(false, sigPubKey);

    BigInteger[] rs = decodeSig(dsaSig);

    Assert.assertTrue(signer.verifySignature(hash, rs[0], rs[1]));

    //
    // Shutdown nodes and close services.
    //
    NodeTestUtil.shutdownNodes();
    keyGenerationService.shutdown();
    signingService.shutdown();
}

From source file:org.cryptoworkshop.ximix.test.tests.ECDSAProcessingTest.java

License:Apache License

private void doMixedMissingTest(SigningService signingService, final ECPublicKeyParameters sigPubKey,
        String[] sigNodes) throws Exception {
    SHA256Digest sha256 = new SHA256Digest();

    byte[] message = "hello world!".getBytes();
    byte[] hash = new byte[sha256.getDigestSize()];

    sha256.update(message, 0, message.length);

    sha256.doFinal(hash, 0);//  www.jav  a  2 s.  co  m

    SignatureGenerationOptions sigGenOptions = new SignatureGenerationOptions.Builder(Algorithm.ECDSA)
            .withThreshold(2).withNodes(sigNodes).build();

    byte[] dsaSig = signingService.generateSignature("ECKEY", sigGenOptions, hash);

    //
    // check the signature locally.
    //
    ECDSASigner signer = new ECDSASigner();

    signer.init(false, sigPubKey);

    BigInteger[] rs = decodeSig(dsaSig);

    Assert.assertTrue(signer.verifySignature(hash, rs[0], rs[1]));
}

From source file:org.diqube.im.IdentityHandler.java

License:Open Source License

@Override
public Ticket login(String userName, String password) throws AuthenticationException, TException {
    if (userName == null || "".equals(userName.trim()))
        throw new AuthenticationException("Empty username.");

    if (password == null || "".equals(password.trim()))
        throw new AuthenticationException("Empty password.");

    if (superuserCheck.isSuperuser(userName)) {
        if (!password.equals(superuserPassword))
            throw new AuthenticationException("Invalid credentials.");

        logger.info("Successful login by superuser '{}'", userName);

        // we have a successfully authenticated superuser!
        return ticketVendor.createDefaultTicketForUser(superuser, true);
    }//from   w  ww .  j a  v  a2s  .co  m

    SUser user;
    try (ClosableProvider<IdentityStateMachine> p = consensusClient
            .getStateMachineClient(IdentityStateMachine.class)) {
        user = p.getClient().getUser(GetUser.local(userName));
    } catch (ConsensusClusterUnavailableException e) {
        logger.warn("Consensus cluster offline, cannot load user!", e);
        user = null;
    }
    if (user == null) {
        logger.info("User '{}' tried to login, but does not exist", userName);
        throw new AuthenticationException("Invalid credentials.");
    }

    byte[] userProvidedPassword = password.getBytes(Charset.forName("UTF-8"));
    byte[] salt = user.getPassword().getSalt();

    BouncyCastleUtil.ensureInitialized();

    PKCS5S2ParametersGenerator pbkdf2sha256 = new PKCS5S2ParametersGenerator(new SHA256Digest());
    pbkdf2sha256.init(userProvidedPassword, salt, PBKDF2_ITERATIONS);
    byte[] userProvidedHash = ((KeyParameter) pbkdf2sha256.generateDerivedParameters(HASH_LENGTH_BYTES * 8))
            .getKey();

    if (!Arrays.equals(userProvidedHash, user.getPassword().getHash())) {
        logger.info("User '{}' provided bad password for login", userName);
        throw new AuthenticationException("Invalid credentials.");
    }

    // authenticated successfully!
    Ticket res = ticketVendor.createDefaultTicketForUser(userName, false);

    logger.info("User '{}' logged in successfully! Returning new ticket {} valid until {}.", userName,
            RUuidUtil.toUuid(res.getClaim().getTicketId()), res.getClaim().getValidUntil());

    return res;
}

From source file:org.diqube.im.IdentityHandler.java

License:Open Source License

private void internalSetUserPassword(SUser user, String newPassword) throws TException {
    BouncyCastleUtil.ensureInitialized();

    byte[] newSalt = new byte[SALT_LENGTH_BYTES];

    if (useStrongRandom) {
        try {//from w w w  . j  a v  a 2  s. c  o m
            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);
}

From source file:org.diqube.ticket.TicketSignatureService.java

License:Open Source License

/**
 * Checks if a {@link Ticket} has a valid signature.
 * //from w  w w .  ja  v  a  2  s  .  c o  m
 * @param deserializedTicket
 *          The result of {@link TicketUtil#deserialize(ByteBuffer)} of the serialized {@link Ticket}.
 * @return true if {@link Ticket} signature is valid.
 */
public boolean isValidTicketSignature(Pair<Ticket, byte[]> deserializedTicket) {
    for (RSAKeyParameters pubKey : keyManager.getPublicValidationKeys()) {
        RSADigestSigner signer = new RSADigestSigner(new SHA256Digest());
        signer.init(false, pubKey);
        signer.update(deserializedTicket.getRight(), 0, deserializedTicket.getRight().length);
        if (signer.verifySignature(deserializedTicket.getLeft().getSignature()))
            return true;
    }
    return false;
}

From source file:org.diqube.ticket.TicketSignatureService.java

License:Open Source License

/**
 * Calculates the signature of a ticket and updates the given {@link Ticket} object directly.
 * /* w  ww  . ja v  a2s  .  c om*/
 * @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);
    }
}

From source file:org.ejbca.util.StringTools.java

License:Open Source License

public static String pbeEncryptStringWithSha256Aes192(final String in)
        throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException {
    if (CryptoProviderTools.isUsingExportableCryptography()) {
        log.warn("Obfuscation not possible due to weak crypto policy.");
        return in;
    }/*  w ww  .  j av a2s. com*/
    final Digest digest = new SHA256Digest();

    final PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(digest);
    pGen.init(PBEParametersGenerator.PKCS12PasswordToBytes(p), getSalt(), iCount);

    final ParametersWithIV params = (ParametersWithIV) pGen.generateDerivedParameters(192, 128);
    final SecretKeySpec encKey = new SecretKeySpec(((KeyParameter) params.getParameters()).getKey(), "AES");
    final Cipher c;
    c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
    c.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV()));

    final byte[] enc = c.doFinal(in.getBytes("UTF-8"));

    final byte[] hex = Hex.encode(enc);
    return new String(hex);
}

From source file:org.ethereum.crypto.CryptoTest.java

License:Open Source License

@Test // ECIES_AES128_SHA256 + No Ephemeral Key + IV(all zeroes)
public void test14() throws Throwable {

    AESEngine aesEngine = new AESEngine();

    IESEngine iesEngine = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA256Digest()),
            new HMac(new SHA256Digest()), new BufferedBlockCipher(new SICBlockCipher(aesEngine)));

    byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };

    IESParameters p = new IESWithCipherParameters(d, e, 64, 128);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[16]);

    ECKeyPairGenerator eGen = new ECKeyPairGenerator();
    KeyGenerationParameters gParam = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());

    eGen.init(gParam);/*ww  w . ja va 2s. c  o  m*/

    AsymmetricCipherKeyPair p1 = eGen.generateKeyPair();
    AsymmetricCipherKeyPair p2 = eGen.generateKeyPair();

    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    generator.init(keygenParams);

    ECKeyPairGenerator gen = new ECKeyPairGenerator();
    gen.init(new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom()));

    iesEngine.init(true, p1.getPrivate(), p2.getPublic(), parametersWithIV);

    byte[] message = Hex.decode("010101");
    log.info("payload: {}", Hex.toHexString(message));

    byte[] cipher = iesEngine.processBlock(message, 0, message.length);
    log.info("cipher: {}", Hex.toHexString(cipher));

    IESEngine decryptorIES_Engine = new IESEngine(new ECDHBasicAgreement(),
            new KDF2BytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()),
            new BufferedBlockCipher(new SICBlockCipher(aesEngine)));

    decryptorIES_Engine.init(false, p2.getPrivate(), p1.getPublic(), parametersWithIV);

    byte[] orig = decryptorIES_Engine.processBlock(cipher, 0, cipher.length);

    log.info("orig: " + Hex.toHexString(orig));
}

From source file:org.ethereum.crypto.CryptoTest.java

License:Open Source License

@Test // ECIES_AES128_SHA256 + Ephemeral Key + IV(all zeroes)
public void test15() throws Throwable {

    byte[] privKey = Hex.decode("a4627abc2a3c25315bff732cb22bc128f203912dd2a840f31e66efb27a47d2b1");

    ECKey ecKey = ECKey.fromPrivate(privKey);

    ECPrivateKeyParameters ecPrivKey = new ECPrivateKeyParameters(ecKey.getPrivKey(), ECKey.CURVE);
    ECPublicKeyParameters ecPubKey = new ECPublicKeyParameters(ecKey.getPubKeyPoint(), ECKey.CURVE);

    AsymmetricCipherKeyPair myKey = new AsymmetricCipherKeyPair(ecPubKey, ecPrivKey);

    AESEngine aesEngine = new AESEngine();

    IESEngine iesEngine = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA256Digest()),
            new HMac(new SHA256Digest()), new BufferedBlockCipher(new SICBlockCipher(aesEngine)));

    byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };

    IESParameters p = new IESWithCipherParameters(d, e, 64, 128);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[16]);

    ECKeyPairGenerator eGen = new ECKeyPairGenerator();
    KeyGenerationParameters gParam = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());

    eGen.init(gParam);//from   w ww.jav  a  2  s  .  com

    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    generator.init(keygenParams);

    EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(generator, new KeyEncoder() {
        public byte[] getEncoded(AsymmetricKeyParameter keyParameter) {
            return ((ECPublicKeyParameters) keyParameter).getQ().getEncoded();
        }
    });

    ECKeyPairGenerator gen = new ECKeyPairGenerator();
    gen.init(new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom()));

    iesEngine.init(myKey.getPublic(), parametersWithIV, kGen);

    byte[] message = Hex.decode("010101");
    log.info("payload: {}", Hex.toHexString(message));

    byte[] cipher = iesEngine.processBlock(message, 0, message.length);
    log.info("cipher: {}", Hex.toHexString(cipher));

    IESEngine decryptorIES_Engine = new IESEngine(new ECDHBasicAgreement(),
            new KDF2BytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()),
            new BufferedBlockCipher(new SICBlockCipher(aesEngine)));

    decryptorIES_Engine.init(myKey.getPrivate(), parametersWithIV, new ECIESPublicKeyParser(ECKey.CURVE));

    byte[] orig = decryptorIES_Engine.processBlock(cipher, 0, cipher.length);

    log.info("orig: " + Hex.toHexString(orig));
}

From source file:org.ethereum.crypto.ECIESCoder.java

License:Open Source License

public static byte[] decrypt(ECPoint ephem, BigInteger prv, byte[] iv, byte[] cipher, byte[] macData)
        throws InvalidCipherTextException {
    AESEngine aesEngine = new AESEngine();

    EthereumIESEngine iesEngine = new EthereumIESEngine(new ECDHBasicAgreement(),
            new ConcatKDFBytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()), new SHA256Digest(),
            new BufferedBlockCipher(new SICBlockCipher(aesEngine)));

    byte[] d = new byte[] {};
    byte[] e = new byte[] {};

    IESParameters p = new IESWithCipherParameters(d, e, KEY_SIZE, KEY_SIZE);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, iv);

    iesEngine.init(false, new ECPrivateKeyParameters(prv, CURVE), new ECPublicKeyParameters(ephem, CURVE),
            parametersWithIV);//  ww w. ja v a  2s .c o  m

    return iesEngine.processBlock(cipher, 0, cipher.length, macData);
}