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

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

Introduction

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

Prototype

public int doFinal(byte[] out, int outOff) 

Source Link

Usage

From source file:dorkbox.util.HashUtil.java

License:Apache License

/**
 * gets the SHA256 hash + SALT of the specified username, as UTF-16
 *//*w  w w . ja v a 2s.c  o m*/
public static byte[] getSha256WithSalt(String username, byte[] saltBytes) {
    if (username == null) {
        return null;
    }

    byte[] charToBytes = Sys.charToBytes16(username.toCharArray());
    byte[] userNameWithSalt = Sys.concatBytes(charToBytes, saltBytes);

    SHA256Digest sha256 = new SHA256Digest();
    byte[] usernameHashBytes = new byte[sha256.getDigestSize()];
    sha256.update(userNameWithSalt, 0, userNameWithSalt.length);
    sha256.doFinal(usernameHashBytes, 0);

    return usernameHashBytes;
}

From source file:dorkbox.util.HashUtil.java

License:Apache License

/**
 * gets the SHA256 hash of the specified string, as UTF-16
 *///from w  w w .j a v a2s  .  c o m
public static byte[] getSha256(String string) {
    byte[] charToBytes = Sys.charToBytes16(string.toCharArray());

    SHA256Digest sha256 = new SHA256Digest();
    byte[] usernameHashBytes = new byte[sha256.getDigestSize()];
    sha256.update(charToBytes, 0, charToBytes.length);
    sha256.doFinal(usernameHashBytes, 0);

    return usernameHashBytes;
}

From source file:dorkbox.util.HashUtil.java

License:Apache License

/**
 * gets the SHA256 hash of the specified byte array
 *///from  w  ww  .j a  va 2  s.  c  o  m
public static byte[] getSha256(byte[] bytes) {

    SHA256Digest sha256 = new SHA256Digest();
    byte[] hashBytes = new byte[sha256.getDigestSize()];
    sha256.update(bytes, 0, bytes.length);
    sha256.doFinal(hashBytes, 0);

    return hashBytes;
}

From source file:dorkbox.util.HashUtil.java

License:Apache License

public static byte[] getSha256WithSalt(byte[] bytes, byte[] saltBytes) {
    if (bytes == null || saltBytes == null) {
        return null;
    }/*from   www.  j  ava 2s .c  o m*/

    byte[] bytesWithSalt = dorkbox.util.Sys.concatBytes(bytes, saltBytes);

    SHA256Digest sha256 = new SHA256Digest();
    byte[] usernameHashBytes = new byte[sha256.getDigestSize()];
    sha256.update(bytesWithSalt, 0, bytesWithSalt.length);
    sha256.doFinal(usernameHashBytes, 0);

    return usernameHashBytes;
}

From source file:dorkbox.util.Sys.java

License:Apache License

/**
 * gets the SHA256 hash + SALT of the specified username, as UTF-16
 *//*ww w.  j a v a2s. c  o m*/
public static byte[] getSha256WithSalt(String username, byte[] saltBytes) {
    if (username == null) {
        return null;
    }

    byte[] charToBytes = Sys.charToBytes(username.toCharArray());
    byte[] userNameWithSalt = Sys.concatBytes(charToBytes, saltBytes);

    SHA256Digest sha256 = new SHA256Digest();
    byte[] usernameHashBytes = new byte[sha256.getDigestSize()];
    sha256.update(userNameWithSalt, 0, userNameWithSalt.length);
    sha256.doFinal(usernameHashBytes, 0);

    return usernameHashBytes;
}

From source file:dorkbox.util.Sys.java

License:Apache License

/**
 * gets the SHA256 hash of the specified string, as UTF-16
 *//*  w  w w.j  a va  2 s  .  com*/
public static byte[] getSha256(String string) {
    byte[] charToBytes = Sys.charToBytes(string.toCharArray());

    SHA256Digest sha256 = new SHA256Digest();
    byte[] usernameHashBytes = new byte[sha256.getDigestSize()];
    sha256.update(charToBytes, 0, charToBytes.length);
    sha256.doFinal(usernameHashBytes, 0);

    return usernameHashBytes;
}

From source file:freemail.HashSlotManager.java

License:Open Source License

@Override
protected String incSlot(String slot) {
    byte[] buf = Base32.decode(slot);
    SHA256Digest sha256 = new SHA256Digest();
    sha256.update(buf, 0, buf.length);//w w w. j a v a 2s.c o  m
    sha256.doFinal(buf, 0);

    return Base32.encode(buf);
}

From source file:freemail.OutboundContact.java

License:Open Source License

/**
 * Set up an outbound contact. Fetch the mailsite, generate a new SSK keypair and post an RTS message to the appropriate KSK.
 * Will block for mailsite retrieval and RTS insertion
 *
 * @return true for success/*from w  w w .jav  a  2 s . c  om*/
 */
private boolean init() throws ConnectionTerminatedException, InterruptedException {
    Logger.normal(this, "Initialising Outbound Contact " + address.toString());

    // try to fetch get all necessary info. will fetch mailsite / generate new keys if necessary
    String initialslot = this.getCurrentLowestSlot();
    SSKKeyPair commssk = this.getCommKeyPair();
    if (commssk == null)
        return false;
    SSKKeyPair ackssk = this.getAckKeyPair();
    RSAKeyParameters their_pub_key = this.getPubKey();
    if (their_pub_key == null)
        return false;
    String rtsksk = this.getRtsKsk();
    if (rtsksk == null)
        return false;

    StringBuffer rtsmessage = new StringBuffer();

    // the public part of the SSK keypair we generated
    rtsmessage.append("commssk=" + commssk.pubkey + "\r\n");

    rtsmessage.append("ackssk=" + ackssk.privkey + "\r\n");

    rtsmessage.append("initialslot=" + initialslot + "\r\n");

    rtsmessage.append("messagetype=rts\r\n");

    // must include who this RTS is to, otherwise we're vulnerable to surreptitious forwarding
    rtsmessage.append("to=" + this.address.getSubDomain() + "\r\n");

    // get our mailsite URI
    String our_mailsite_uri = account.getProps().get("mailsite.pubkey");

    rtsmessage.append("mailsite=" + our_mailsite_uri + "\r\n");

    rtsmessage.append("\r\n");
    //FreemailLogger.normal(this,rtsmessage.toString());

    // sign the message
    SHA256Digest sha256 = new SHA256Digest();
    sha256.update(rtsmessage.toString().getBytes(), 0, rtsmessage.toString().getBytes().length);
    byte[] hash = new byte[sha256.getDigestSize()];
    sha256.doFinal(hash, 0);

    RSAKeyParameters our_priv_key = AccountManager.getPrivateKey(account.getProps());

    AsymmetricBlockCipher sigcipher = new RSAEngine();
    sigcipher.init(true, our_priv_key);
    byte[] sig = null;
    try {
        sig = sigcipher.processBlock(hash, 0, hash.length);
    } catch (InvalidCipherTextException icte) {
        Logger.error(this, "Failed to RSA encrypt hash: " + icte.getMessage());
        icte.printStackTrace();
        return false;
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        bos.write(rtsmessage.toString().getBytes());
        bos.write(sig);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return false;
    }

    // make up a symmetric key
    PaddedBufferedBlockCipher aescipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
            new PKCS7Padding());

    // quick paranoia check!
    if (aescipher.getBlockSize() != AES_BLOCK_LENGTH) {
        // bouncycastle must have changed their implementation, so 
        // we're in trouble
        Logger.normal(this,
                "Incompatible block size change detected in cryptography API! Are you using a newer version of the bouncycastle libraries? If so, we suggest you downgrade for now, or check for a newer version of Freemail.");
        return false;
    }

    byte[] aes_iv_and_key = this.getAESParams();

    // now encrypt that with our recipient's public key
    AsymmetricBlockCipher enccipher = new RSAEngine();
    enccipher.init(true, their_pub_key);
    byte[] encrypted_aes_params = null;
    try {
        encrypted_aes_params = enccipher.processBlock(aes_iv_and_key, 0, aes_iv_and_key.length);
    } catch (InvalidCipherTextException icte) {
        Logger.error(this,
                "Failed to perform asymmertic encryption on RTS symmetric key: " + icte.getMessage());
        icte.printStackTrace();
        return false;
    }

    // now encrypt the message with the symmetric key
    KeyParameter kp = new KeyParameter(aes_iv_and_key, aescipher.getBlockSize(), AES_KEY_LENGTH);
    ParametersWithIV kpiv = new ParametersWithIV(kp, aes_iv_and_key, 0, aescipher.getBlockSize());
    aescipher.init(true, kpiv);

    byte[] encmsg = new byte[aescipher.getOutputSize(bos.toByteArray().length) + encrypted_aes_params.length];
    System.arraycopy(encrypted_aes_params, 0, encmsg, 0, encrypted_aes_params.length);
    int offset = encrypted_aes_params.length;
    offset += aescipher.processBytes(bos.toByteArray(), 0, bos.toByteArray().length, encmsg, offset);

    try {
        aescipher.doFinal(encmsg, offset);
    } catch (InvalidCipherTextException icte) {
        Logger.error(this, "Failed to perform symmertic encryption on RTS data: " + icte.getMessage());
        icte.printStackTrace();
        return false;
    }

    // insert it!
    HighLevelFCPClient cli = new HighLevelFCPClient();
    if (cli.slotInsert(encmsg, "KSK@" + rtsksk + "-" + DateStringFactory.getKeyString(), 1, "") < 0) {
        // safe to copy the message into the contact outbox though
        return false;
    }

    // remember the fact that we have successfully inserted the rts
    this.contactfile.put("status", "rts-sent");
    // and remember when we sent it!
    this.contactfile.put("rts-sent-at", Long.toString(System.currentTimeMillis()));
    // and since that's been successfully inserted to that key, we can
    // throw away the symmetric key
    this.contactfile.remove("aesparams");

    Logger.normal(this, "Succesfully initialised Outbound Contact");

    return true;
}

From source file:freemail.OutboundContact.java

License:Open Source License

private String popNextSlot() {
    String slot = this.contactfile.get("nextslot");
    if (slot == null) {
        return generateFirstSlot();
    }//from w  w w  .ja  v a 2 s. c om
    SHA256Digest sha256 = new SHA256Digest();
    sha256.update(Base32.decode(slot), 0, Base32.decode(slot).length);
    byte[] nextslot = new byte[sha256.getDigestSize()];
    sha256.doFinal(nextslot, 0);
    this.contactfile.put("nextslot", Base32.encode(nextslot));

    return slot;
}

From source file: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 v  a2 s .co  m

    // 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;
    try {
        rtsfile = File.createTempFile("rtstmp", "tmp", Freemail.getTempDir());

        ByteArrayInputStream bis = new ByteArrayInputStream(plaintext);
        LineReadingInputStream lis = new LineReadingInputStream(bis);
        PrintStream 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);
        }

        ps.close();

        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;
        }

        bis.close();
    } catch (IOException ioe) {
        Logger.normal(this, "IO error whilst handling RTS message. " + ioe.getMessage());
        ioe.printStackTrace();
        if (rtsfile != null)
            rtsfile.delete();
        return false;
    }

    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_raw = 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();

    FreenetURI their_mailsite_furi;
    try {
        their_mailsite_furi = new FreenetURI(their_mailsite_raw);
    } catch (MalformedURLException mfue) {
        Logger.normal(this, "Mailsite in the RTS message is not a valid Freenet URI. Discarding RTS message.");
        rtsfile.delete();
        return true;
    }

    String their_mailsite = "USK@" + their_mailsite_furi.getKeyBody() + "/" + their_mailsite_furi.getSuffix();

    if (!their_mailsite.endsWith("/")) {
        their_mailsite += "/";
    }
    their_mailsite += AccountManager.MAILSITE_VERSION + "/" + MailSite.MAILPAGE;

    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);

        //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
    String our_mailsite_keybody;
    try {
        our_mailsite_keybody = new FreenetURI(account.getProps().get("mailsite.pubkey")).getKeyBody();
    } catch (MalformedURLException mfue) {
        Logger.normal(this, "Local mailsite URI is invalid! Corrupt account file?");
        msfile.delete();
        rtsfile.delete();
        return false;
    }

    String our_domain_alias = account.getProps().get("domain_alias");
    FreenetURI mailsite_furi;
    try {
        mailsite_furi = new FreenetURI(our_mailsite_keybody);
    } catch (MalformedURLException mfe) {
        msfile.delete();
        rtsfile.delete();
        return false;
    }
    String our_subdomain = Base32.encode(mailsite_furi.getKeyBody().getBytes());

    if (!rtsprops.get("to").equalsIgnoreCase(our_subdomain) && our_domain_alias != null
            && !rtsprops.get("to").equals(our_domain_alias)) {
        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 :)");

    // create the inbound contact
    InboundContact ibct = new InboundContact(this.contact_dir, their_mailsite_furi);

    ibct.setProp("commssk", rtsprops.get("commssk"));
    String ackssk = rtsprops.get("ackssk");
    if (!ackssk.endsWith("/"))
        ackssk += "/";
    ibct.setProp("ackssk", ackssk);
    ibct.setProp("slots", rtsprops.get("initialslot"));

    // insert the cts at some point
    AckProcrastinator.put(ackssk + "cts");

    msfile.delete();
    rtsfile.delete();

    Logger.normal(this, "Inbound contact created!");

    return true;
}