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

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

Introduction

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

Prototype

public void update(byte[] in, int inOff, int len) 

Source Link

Usage

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;
    }// w w  w  .  j  a va 2s . com

    // 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);
    sha256.doFinal(buf, 0);//ww w  .ja v  a  2  s . com

    return Base32.encode(buf);
}

From source file:org.jcryptool.visual.hashing.views.HashingView.java

License:Open Source License

private String computeHash(String hashName, String inputText, Text hashText) {
    hash = hash.getName(hashName);//from  w ww  .  ja va2 s  . c  o m
    byte[] digest = null;
    switch (hash) {
    case MD2:
        MD2Digest md2 = new MD2Digest();
        md2.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[md2.getDigestSize()];
        md2.doFinal(digest, 0);

        break;
    case MD4:
        MD4Digest md4 = new MD4Digest();
        md4.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[md4.getDigestSize()];
        md4.doFinal(digest, 0);

        break;
    case MD5:
        MD5Digest md5 = new MD5Digest();
        md5.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[md5.getDigestSize()];
        md5.doFinal(digest, 0);

        break;
    case SHA1:
        SHA1Digest sha1 = new SHA1Digest();
        sha1.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha1.getDigestSize()];
        sha1.doFinal(digest, 0);

        break;
    case SHA256:
        SHA256Digest sha256 = new SHA256Digest();
        sha256.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha256.getDigestSize()];
        sha256.doFinal(digest, 0);

        break;
    case SHA512:
        SHA512Digest sha512 = new SHA512Digest();
        sha512.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha512.getDigestSize()];
        sha512.doFinal(digest, 0);

        break;
    case SHA3_224:
        SHA3.Digest224 sha3_224 = new SHA3.Digest224();
        sha3_224.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_224.getDigestLength()];
        digest = sha3_224.digest();

        break;
    case SHA3_256:
        SHA3.Digest256 sha3_256 = new SHA3.Digest256();
        sha3_256.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_256.getDigestLength()];
        digest = sha3_256.digest();

        break;
    case SHA3_384:
        SHA3.Digest384 sha3_384 = new SHA3.Digest384();
        sha3_384.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_384.getDigestLength()];
        digest = sha3_384.digest();

        break;
    case SHA3_512:
        SHA3.Digest512 sha3_512 = new SHA3.Digest512();
        sha3_512.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_512.getDigestLength()];
        digest = sha3_512.digest();

        break;
    case SKEIN_256:
        Skein.Digest_256_256 skein_256 = new Skein.Digest_256_256();
        skein_256.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[skein_256.getDigestLength()];
        digest = skein_256.digest();

        break;
    case SKEIN_512:
        Skein.Digest_512_512 skein_512 = new Skein.Digest_512_512();
        skein_512.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[skein_512.getDigestLength()];
        digest = skein_512.digest();

        break;
    case SKEIN_1024:
        Skein.Digest_1024_1024 skein_1024 = new Skein.Digest_1024_1024();
        skein_1024.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[skein_1024.getDigestLength()];
        digest = skein_1024.digest();

        break;
    case RIPEMD160:
        RIPEMD160Digest ripemd160 = new RIPEMD160Digest();
        ripemd160.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[ripemd160.getDigestSize()];
        ripemd160.doFinal(digest, 0);

        break;
    case SM3:
        SM3Digest sm3 = new SM3Digest();
        sm3.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sm3.getDigestSize()];
        sm3.doFinal(digest, 0);

        break;
    case TIGER:
        TigerDigest tiger = new TigerDigest();
        tiger.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[tiger.getDigestSize()];
        tiger.doFinal(digest, 0);

        break;
    case GOST3411:
        GOST3411Digest gost3411 = new GOST3411Digest();
        gost3411.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[gost3411.getDigestSize()];
        gost3411.doFinal(digest, 0);

        break;
    case WHIRLPOOL:
        WhirlpoolDigest whirlpool = new WhirlpoolDigest();
        whirlpool.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[whirlpool.getDigestSize()];
        whirlpool.doFinal(digest, 0);

        break;
    default:
        break;
    }

    String hashHexValue = new String(Hex.encode(digest));
    if (btnHexadezimal.getSelection()) {
        String hashValueOutput = hashHexValue.toUpperCase().replaceAll(".{2}", "$0 "); //$NON-NLS-1$ //$NON-NLS-2$
        hashText.setText(hashValueOutput);
    } else if (btnDezimal.getSelection()) {
        String hashValue = hexToDecimal(hashHexValue);
        hashValue = hashValue.replaceAll(".{3}", "$0 "); //$NON-NLS-1$ //$NON-NLS-2$
        hashText.setText(hashValue);
    } else if (btnBinary.getSelection()) {
        String hashValue = hexToBinary(hashHexValue);
        hashValue = hashValue.replaceAll(".{8}", "$0#"); //$NON-NLS-1$ //$NON-NLS-2$
        hashText.setText(hashValue);
    }

    return hashHexValue;
}

From source file:org.opendaylight.capwap.dtls.DtlsUtils.java

License:Open Source License

static byte[] sha256DigestOf(byte[] input) {
    SHA256Digest d = new SHA256Digest();
    d.update(input, 0, input.length);
    byte[] result = new byte[d.getDigestSize()];
    d.doFinal(result, 0);//ww w  .  j  av a 2 s .  co  m
    return result;
}

From source file:org.pwsafe.lib.crypto.SHA256Pws.java

License:Open Source License

public static byte[] digest(byte[] incoming) {

    SHA256Digest digest = new SHA256Digest();
    byte[] output = new byte[digest.getDigestSize()];

    digest.update(incoming, 0, incoming.length);
    digest.doFinal(output, 0);//from   w  ww . j  ava  2 s  .c  o m

    return output;

}

From source file:org.pwsafe.lib.crypto.SHA256Pws.java

License:Open Source License

private static byte[] digestNJava(byte[] p, int iter) {
    SHA256Digest digest = new SHA256Digest();
    byte[] output = new byte[digest.getDigestSize()];
    byte[] input = new byte[digest.getDigestSize()];
    byte[] t;/*from ww  w .jav a2 s . co m*/

    digest.update(p, 0, p.length);
    digest.doFinal(output, 0);

    for (int i = 0; i < iter; ++i) {
        t = input;
        input = output;
        output = t;

        digest.reset();
        digest.update(input, 0, input.length);
        digest.doFinal(output, 0);
    }

    return output;
}

From source file:org.satochip.satochipclient.CardConnectorTest.java

License:Apache License

public void testCardParseTransaction(byte keynbr) throws CardConnectorException, ECException {

    // recover pubkey
    byte[] pubkey, response;
    CardDataParser.PubKeyData dataparser = new CardDataParser.PubKeyData(authentikey);
    if (keynbr == bip32_keynbr) {
        response = cc.cardBip32GetExtendedKey(default_bip32path);
        authentikey = dataparser.parseBip32GetExtendedKey(response).authentikey;
        pubkey = dataparser.pubkey;/*from w ww  .  j  a  v a 2  s .c om*/
    } else {
        response = cc.cardGetPublicKeyFromPrivate(keynbr);
        pubkey = dataparser.parseGetPublicKeyFromPrivate(response).pubkey;
    }

    // bitcoinj
    NetworkParameters params;
    params = RegTestParams.get();
    Transaction tx = new Transaction(params);
    ECKey serverKey = new ECKey(null, pubkey, true);
    BigInteger nanoCoins = Utils.toNanoCoins(1, 0);
    TransactionOutput outputToMe = new TransactionOutput(params, tx, nanoCoins, serverKey);

    // simple tx
    tx.addOutput(outputToMe);
    tx.addInput(new TransactionInput(params, tx, outputToMe.getScriptBytes()));

    int inputIndex = 0;
    byte[] connectedScript = outputToMe.getScriptBytes();
    byte sigHashType = (byte) TransactionSignature.calcSigHashValue(SigHash.ALL, false);
    byte[] rawtxforhashing = byteArrayForSignature(tx, inputIndex, connectedScript, sigHashType);

    // unused
    System.out.println("Raw tx for hashing:" + toHexString(rawtxforhashing));
    byte[] rawtxhash = new byte[32];
    SHA256Digest sha256 = new SHA256Digest();
    sha256.reset();
    sha256.update(rawtxforhashing, 0, rawtxforhashing.length);
    sha256.doFinal(rawtxhash, 0);
    //System.out.println("Raw tx singlehash:" + toString(rawtxhash));
    sha256.reset();
    sha256.update(rawtxhash, 0, rawtxhash.length);
    sha256.doFinal(rawtxhash, 0);
    //System.out.println("Raw tx doublehash:" + toString(rawtxhash));

    Sha256Hash rawtxhash2 = tx.hashForSignature(inputIndex, connectedScript, sigHashType);
    byte[] txhash_sw = rawtxhash2.getBytes();
    System.out.println("Tx hash Bitcoinj: " + toHexString(txhash_sw));

    // send to card for parsing
    //byte[] response= cc.cardParseTransaction(rawtxforhashing);
    response = cc.cardParseTx(rawtxforhashing);
    CardDataParser.PubKeyData txparser = new CardDataParser.PubKeyData(authentikey);
    byte[] txhash_hw = txparser.parseTxHash(response).data; //Arrays.copyOfRange(response, 2, 2+32);
    System.out.println("Tx hash SatoChip: " + toHexString(txhash_hw));
    System.out.println(txparser.toString());
    assertArrayEquals(txhash_hw, txhash_sw);

    // check if 2fa is required
    boolean need_2fa_chalresp = ((txparser.option_flags & 0x8000) == 0x8000) ? true : false; // if msb is set, a challenge-response 2nd factor authentification is needed
    byte[] txhmac = null;
    if (need_2fa_chalresp) {
        try {
            System.out.println("Second factor authentication required for challenge response...");
            System.out.println("Please insert a configured yubikey!");
            MILLISECONDS.sleep(2000);
        } catch (InterruptedException ex) {
        }
        YubikeyConnector yubikey = new YubikeyConnector(false);
        yubikey.findYubikey(YubikeyConnector.PRODUCT_ID_NEO);
        yubikey.openYubikey();
        yubikey.attachYubikeyInterface();
        txhmac = yubikey.challenge_response(txhash_hw, YubikeyConnector.MODE_HMAC, YubikeyConnector.SLOT_2,
                false, true);
        yubikey.releaseYubikeyInterface();
        yubikey.closeYubikey();
        System.out.println("txhmac: " + toHexString(txhmac));
        // test with wrong hmac:
        //txhmac[0]=0;
    }
    byte[] txsign = cc.cardSignTransaction(keynbr, txhash_hw, txhmac);
    System.out.println("txsign: " + toHexString(txsign));

}

From source file:org.toporin.bitcoincore.ECKey.java

License:Apache License

public static byte[] recoverFromSignature(int recID, byte[] msg, byte[] sig, boolean doublehash)
        throws ECException {

    //return CardConnector.recoverPublicKeyFromSig(recID, msg, sig, doublehash);

    byte[] digest = new byte[32];
    SHA256Digest sha256 = new SHA256Digest();
    sha256.reset();/*from ww  w. j av a  2 s. c o  m*/
    sha256.update(msg, 0, msg.length);
    sha256.doFinal(digest, 0);
    if (doublehash) {
        sha256.reset();
        sha256.update(digest, 0, digest.length);
        sha256.doFinal(digest, 0);
    }
    BigInteger bi = new BigInteger(1, digest);
    ECDSASignature ecdsaSig = new ECDSASignature(sig);
    ECKey k = ECKey.recoverFromSignature(recID, ecdsaSig, bi, true);

    if (k != null)
        return k.getPubKey();
    else
        return null;

}