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.ethereum.crypto.ECIESCoder.java

License:Open Source License

private static EthereumIESEngine makeIESEngine(boolean isEncrypt, ECPoint pub, BigInteger prv, byte[] iv) {
    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(isEncrypt, new ECPrivateKeyParameters(prv, CURVE), new ECPublicKeyParameters(pub, CURVE),
            parametersWithIV);/*from ww  w  .j  a  v a  2 s .co  m*/
    return iesEngine;
}

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

License:Open Source License

@Test
public void testKDF() {
    ConcatKDFBytesGenerator kdf = new ConcatKDFBytesGenerator(new SHA256Digest());
    kdf.init(new KDFParameters("Hello".getBytes(), new byte[0]));
    byte[] bytes = new byte[2];
    kdf.generateBytes(bytes, 0, bytes.length);
    assertArrayEquals(new byte[] { -66, -89 }, bytes);
}

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

License:Open Source License

private static EthereumIESEngine makeIESEngine(boolean isEncrypt, ECPoint pub, BigInteger prv, byte[] IV) {
    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(isEncrypt, new ECPrivateKeyParameters(prv, curve), new ECPublicKeyParameters(pub, curve),
            parametersWithIV);//from w  ww. j  ava 2 s . com
    return iesEngine;
}

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

License:Open Source License

/**
 * Signs the given hash and returns the R and S components as BigIntegers
 * and put them in ECDSASignature//from  w  w w .ja  v a2s. co  m
 *
 * @param input to sign
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
    // No decryption of private key required.
    if (priv == null) {
        throw new MissingPrivateKeyException();
    }
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(priv, CURVE);
    signer.init(true, privKey);
    BigInteger[] components = signer.generateSignature(input);
    return new ECDSASignature(components[0], components[1]).toCanonicalised();
}

From source file:org.fnppl.opensdx.security.SecurityHelper.java

License:Open Source License

public static byte[] getSHA256LocalProof(Vector<Element> ve) throws Exception {
    byte[] ret = new byte[32];//256 bit = 32 byte
    SHA256Digest sha256 = new SHA256Digest();
    //System.out.println("--- sha1localproof ---");
    for (Element e : ve) {
        rekursiveUpdateSHA256(sha256, e);
    }//from   w w  w. j a va  2  s  .  c  om
    sha256.doFinal(ret, 0);
    //System.out.println("--- RESULT ----");
    //System.out.println(SecurityHelper.HexDecoder.encode(ret, ':',-1));
    return ret;
}

From source file:org.forgerock.openicf.framework.remote.SecurityUtil.java

License:CDDL license

/**
 * Generate Secure Remote Password (SRP)
 *
 * @param username user name (aka "identity")
 * @param password password/*from   ww  w .j  a v  a 2  s . c o  m*/
 * @param random   the source of randomness for this generator
 * @param params   group parameters (prime, generator)
 * @return generated verifier and random
 */
public static Pair<String, byte[]> generateVerifier(String username, String password, SecureRandom random,
        SRPGroupParameter params) {
    byte[] I = username.getBytes();
    byte[] P = password.getBytes();
    byte[] s = new byte[16];
    random.nextBytes(s);

    SRP6VerifierGenerator gen = new SRP6VerifierGenerator();
    gen.init(params.N, params.g, new SHA256Digest());
    BigInteger v = gen.generateVerifier(s, I, P);
    return Pair.of(v.toString(16), s);
}

From source file:org.forgerock.openicf.framework.remote.SecurityUtil.java

License:CDDL license

/**
 * Verifies the client and server secret.
 *
 * @param username     user name (aka "identity")
 * @param password     password/*  w  w  w .jav a2 s . c om*/
 * @param verification
 * @param random       the source of randomness for this generator
 * @param params       group parameters (prime, generator)
 * @return true if client and server secret is equals
 * @throws CryptoException If client or server's credentials are invalid
 */
public static boolean checkMutualVerification(String username, String password,
        Pair<String, byte[]> verification, SecureRandom random, SRPGroupParameter params)
        throws CryptoException {

    byte[] I = username.getBytes();
    byte[] P = password.getBytes();
    byte[] s = verification.second;
    BigInteger v = new BigInteger(verification.first, 16);

    SRP6Client client = new SRP6Client();
    client.init(params.N, params.g, new SHA256Digest(), random);

    SRP6Server server = new SRP6Server();
    server.init(params.N, params.g, v, new SHA256Digest(), random);

    BigInteger A = client.generateClientCredentials(s, I, P);
    BigInteger B = server.generateServerCredentials();

    BigInteger clientS = client.calculateSecret(B);
    BigInteger serverS = server.calculateSecret(A);

    return clientS.equals(serverS);
}

From source file:org.freenetproject.freemail.RTSFetcher.java

License:Open Source License

private boolean handle_rts(File rtsmessage) throws ConnectionTerminatedException, InterruptedException {
    // sanity check!
    if (!rtsmessage.exists())
        return false;

    if (rtsmessage.length() > RTS_MAX_SIZE) {
        Logger.normal(this, "RTS Message is too large - discarding!");
        return true;
    }/*from  w w  w .j av a  2 s . c  om*/

    // decrypt
    byte[] plaintext;
    try {
        plaintext = decrypt_rts(rtsmessage);
    } catch (IOException ioe) {
        Logger.normal(this, "Error reading RTS message!");
        return false;
    } catch (InvalidCipherTextException icte) {
        Logger.normal(this, "Could not decrypt RTS message - discarding. " + icte.getMessage());
        return true;
    }

    File rtsfile = null;
    byte[] their_encrypted_sig;
    int messagebytes = 0;
    LineReadingInputStream lis = null;
    PrintStream ps = null;
    try {
        rtsfile = File.createTempFile("rtstmp", "tmp", Freemail.getTempDir());

        ByteArrayInputStream bis = new ByteArrayInputStream(plaintext);
        lis = new LineReadingInputStream(bis);
        ps = new PrintStream(new FileOutputStream(rtsfile));

        String line;
        while (true) {
            try {
                line = lis.readLine(200, 200, false);
            } catch (TooLongException tle) {
                Logger.normal(this, "RTS message has lines that are too long. Discarding.");
                rtsfile.delete();
                return true;
            }
            messagebytes += lis.getLastBytesRead();

            if (line == null || line.equals(""))
                break;
            //FreemailLogger.normal(this, line);

            ps.println(line);
        }

        if (line == null) {
            // that's not right, we shouldn't have reached the end of the file, just the blank line before the signature

            Logger.normal(this, "Couldn't find signature on RTS message - ignoring!");
            rtsfile.delete();
            return true;
        }

        // read the rest of the file into a byte array.
        // will probably have extra stuff on the end because
        // the byte array returned by the decrypt function
        // isn't resized when we know how much plaintext
        // there is. It would be a waste of time, we know
        // we have to read exactly one RSA block's worth.
        their_encrypted_sig = new byte[bis.available()];

        int totalread = 0;
        while (true) {
            int read = bis.read(their_encrypted_sig, totalread, bis.available());
            if (read <= 0)
                break;
            totalread += read;
        }
    } catch (IOException ioe) {
        Logger.normal(this, "IO error whilst handling RTS message. " + ioe.getMessage());
        ioe.printStackTrace();
        if (rtsfile != null)
            rtsfile.delete();
        return false;
    } finally {
        if (ps != null) {
            ps.close();
        }
        if (lis != null) {
            try {
                lis.close();
            } catch (IOException e) {
                Logger.error(this, "Caugth IOException while closing input", e);
            }
        }
    }

    PropsFile rtsprops = PropsFile.createPropsFile(rtsfile);

    try {
        validate_rts(rtsprops);
    } catch (Exception e) {
        Logger.normal(this,
                "RTS message does not contain vital information: " + e.getMessage() + " - discarding");
        rtsfile.delete();
        return true;
    }

    // verify the signature
    String their_mailsite = rtsprops.get("mailsite");

    SHA256Digest sha256 = new SHA256Digest();
    sha256.update(plaintext, 0, messagebytes);
    byte[] our_hash = new byte[sha256.getDigestSize()];
    sha256.doFinal(our_hash, 0);

    HighLevelFCPClient fcpcli = new HighLevelFCPClient();

    Logger.normal(this, "Trying to fetch sender's mailsite: " + their_mailsite);
    File msfile;
    try {
        msfile = fcpcli.fetch(their_mailsite);
    } catch (FCPFetchException fe) {
        // oh well, try again in a bit
        rtsfile.delete();
        return false;
    } catch (FCPException e) {
        Logger.error(this, "Unknown error while checking sender's mailsite: " + e.getMessage());

        //Try again later
        rtsfile.delete();
        return false;
    }

    PropsFile mailsite = PropsFile.createPropsFile(msfile);
    String their_exponent = mailsite.get("asymkey.pubexponent");
    String their_modulus = mailsite.get("asymkey.modulus");

    if (their_exponent == null || their_modulus == null) {
        Logger.normal(this,
                "Mailsite fetched successfully but missing vital information! Discarding this RTS.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    RSAKeyParameters their_pubkey = new RSAKeyParameters(false, new BigInteger(their_modulus, 32),
            new BigInteger(their_exponent, 32));
    AsymmetricBlockCipher deccipher = new RSAEngine();
    deccipher.init(false, their_pubkey);

    byte[] their_hash;
    try {
        their_hash = deccipher.processBlock(their_encrypted_sig, 0, deccipher.getInputBlockSize());
    } catch (InvalidCipherTextException icte) {
        Logger.normal(this,
                "It was not possible to decrypt the signature of this RTS message. Discarding the RTS message.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    // finally we can now check that our hash and their hash
    // match!
    if (their_hash.length < our_hash.length) {
        Logger.normal(this, "The signature of the RTS message is not valid (our hash: " + our_hash.length
                + "bytes, their hash: " + their_hash.length + "bytes. Discarding the RTS message.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }
    int i;
    for (i = 0; i < our_hash.length; i++) {
        if (their_hash[i] != our_hash[i]) {
            Logger.normal(this, "The signature of the RTS message is not valid. Discarding the RTS message.");
            msfile.delete();
            rtsfile.delete();
            return true;
        }
    }
    Logger.normal(this, "Signature valid :)");
    // the signature is valid! Hooray!
    // Now verify the message is for us
    if (!account.getIdentity().equals(rtsprops.get("to"))) {
        Logger.normal(this, "Recieved an RTS message that was not intended for the recipient. Discarding.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    Logger.normal(this, "Original message intended for us :)");

    //Clean up temp files
    if (!msfile.delete()) {
        Logger.error(this, "Couldn't delete fetched mailsite: " + msfile);
    }
    if (!rtsfile.delete()) {
        Logger.error(this, "Couldn't delete rts file: " + rtsfile);
    }

    account.getMessageHandler().createChannelFromRTS(rtsprops);

    return true;
}

From source file:org.freenetproject.freemail.transport.Channel.java

License:Open Source License

private String calculateNextSlot(String slot) {
    byte[] buf = Base32.decode(slot);
    SHA256Digest sha256 = new SHA256Digest();
    sha256.update(buf, 0, buf.length);/*w ww  . java 2s.  c o m*/
    sha256.doFinal(buf, 0);

    return Base32.encode(buf);
}

From source file:org.freenetproject.freemail.transport.Channel.java

License:Open Source License

private String generateRandomSlot() {
    SHA256Digest sha256 = new SHA256Digest();
    byte[] buf = new byte[sha256.getDigestSize()];
    Freemail.getRNG().nextBytes(buf);/*from www  .ja va  2 s .  c  o  m*/
    return Base32.encode(buf);
}