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:edu.vt.middleware.crypt.digest.SHA256.java

License:Open Source License

/** Creates an uninitialized instance of an SHA256 digest. */
public SHA256() {
    super(new SHA256Digest());
}

From source file:edu.vt.middleware.crypt.digest.SHA256.java

License:Open Source License

/**
 * Creates a new SHA256 digest that may optionally be initialized with random
 * data.//  w  w  w .  j  a v  a 2s.  c  o m
 *
 * @param  randomize  True to randomize initial state of digest, false
 * otherwise.
 */
public SHA256(final boolean randomize) {
    super(new SHA256Digest());
    if (randomize) {
        setRandomProvider(new SecureRandom());
        setSalt(getRandomSalt());
    }
}

From source file:edu.vt.middleware.crypt.digest.SHA256.java

License:Open Source License

/**
 * Creates a new SHA256 digest and initializes it with the given salt.
 *
 * @param  salt  Salt data used to initialize digest computation.
 *//* ww w  .ja va2 s. co  m*/
public SHA256(final byte[] salt) {
    super(new SHA256Digest());
    setSalt(salt);
}

From source file:eg.nileu.cis.nilestore.cryptography.SHA256d.java

License:Open Source License

/**
 * Instantiates a new sH a256d.//w w w  .j  a  va  2  s.co  m
 * 
 * @param truncate_to
 *            the truncate_to
 */
public SHA256d(int truncate_to) {

    this.hasher = new SHA256Digest();
    this.truncate_to = truncate_to > hasher.getDigestSize() ? hasher.getDigestSize() : truncate_to;
    this.digest = new byte[truncate_to];
    ;
}

From source file:eg.nileu.cis.nilestore.cryptography.SHA256d.java

License:Open Source License

/**
 * Instantiates a new sH a256d.// w w w .j  a  v a2s  .c o  m
 */
public SHA256d() {
    this.hasher = new SHA256Digest();
    this.digest = new byte[hasher.getDigestSize()];
    ;
    this.truncate_to = hasher.getDigestSize();
}

From source file:emailsecurity.ClientSendMailLayout.java

@Override
public void actionPerformed(ActionEvent e) {
    this.toAddress = this.toTextField.getText();
    this.subject = this.subjectTextField.getText();
    //this.body = this.bodyTextField.getText();
    KeyGenerator key;// www  .  j a  v  a2s  .c o  m
    KeyGenerator iv;
    KeyGenerator mKey;
    byte[] ivValue = new byte[16];
    byte[] ivTemp = new byte[16];
    //SecretKey sKey;
    try {
        key = KeyGenerator.getInstance("AES");
        key.init(128);
        SecretKey sKey = key.generateKey();
        iv = KeyGenerator.getInstance("AES");
        iv.init(128);
        SecretKey siv = iv.generateKey();
        mKey = KeyGenerator.getInstance("AES");
        mKey.init(128);
        SecretKey macKey = mKey.generateKey();

        Digest digest = new SHA256Digest();
        HMac hmac = new HMac(digest);
        hmac.init(new KeyParameter(macKey.getEncoded()));

        System.out.println("IVTEMP = " + ivTemp);
        AESBouncyCastle a = new AESBouncyCastle();
        a.setKeyAndIV(sKey.getEncoded(), siv.getEncoded());

        String messageInString = Base64.getEncoder().encodeToString(macKey.getEncoded())
                + this.bodyTextField.getText();
        byte[] messageInBytes = messageInString.getBytes("UTF-8");

        byte[] encMessageInBytes = a.encrypt(messageInBytes);
        System.out.println("Length of Enc Message = " + encMessageInBytes.length);
        String encMessageInString = Base64.getEncoder().encodeToString(encMessageInBytes);//new String(encMessageInBytes, "UTF-8");
        String temp = new String(messageInBytes, "UTF-8");
        for (int i = 0; i < messageInBytes.length; i++) {
            System.out.println(messageInBytes[i]);
        }
        System.out.println(temp);
        hmac.update(Base64.getDecoder().decode(encMessageInString), 0,
                Base64.getDecoder().decode(encMessageInString).length);
        byte[] macTagInBytes = new byte[digest.getDigestSize()];
        hmac.doFinal(macTagInBytes, 0);
        String tagInString = Base64.getEncoder().encodeToString(macTagInBytes);
        //this.body = Base64.getEncoder().encodeToString(siv.getEncoded())+ "---" + Base64.getEncoder().encodeToString(sKey.getEncoded()) + encMessageInString.length() + "Separator" + encMessageInString;
        System.out.println("Size of tag in string = " + tagInString.length());

        /*------------------For Troubleshooting AES Decryption Errors-------------------
            String ivInString = Base64.getEncoder().encodeToString(siv.getEncoded());
            String keyInString = Base64.getEncoder().encodeToString(sKey.getEncoded());
            byte[] decodedIV = Base64.getDecoder().decode(ivInString);
            SecretKey originalIV = new SecretKeySpec(decodedIV, "AES");
            byte[] decodedKey = Base64.getDecoder().decode(ivInString);
            SecretKey originalKey = new SecretKeySpec(decodedKey, "AES");
            AESBouncyCastle a2 = new AESBouncyCastle();
            a2.setKeyAndIV(sKey.getEncoded(), siv.getEncoded());
            String temp2 = new String(a2.decrypt(Base64.getDecoder().decode(encMessageInString)));
            -----------------------------------------------------------------------------------------*/

        PublicKey publicKeyOfReceiver;
        //PrivateKey privateKeyOfReceiver;
        try {
            publicKeyOfReceiver = readRSAPublicKey("public_keys" + File.separator + this.toAddress);
            //privateKeyOfReceiver = readRSAPrivateKey();
            String publicKeyString = Base64.getEncoder().encodeToString(publicKeyOfReceiver.getEncoded());//readFileAsString("id_rsa.pub");
            //String privateKeyString = Base64.getEncoder().encodeToString(privateKeyOfReceiver.getEncoded());//readFileAsString("id_rsa");

            RSABouncyCastle rsa = new RSABouncyCastle();

            //String tempString = "Akash SIngh";
            //byte[] byteArrayOfKey = tempString.getBytes("UTF-8");//sKey.getEncoded();
            byte[] encryptedKey = rsa.encrypt(sKey.getEncoded(), publicKeyString);
            String encryptedKeyInString = Base64.getEncoder().encodeToString(encryptedKey);
            System.out.println("RSA Encrypted key = " + encryptedKeyInString);
            //byte[] encryptedMacKey = rsa.encrypt(macKey.getEncoded(), publicKeyString);
            //String encryptedMacKeyInString = Base64.getEncoder().encodeToString(encryptedMacKey);

            //byte[] decryptedKey = rsa.decrypt(encryptedKey, privateKeyString);
            //String decryptedKeyInString = Base64.getEncoder().encodeToString(decryptedKey);//new String(decryptedKey, "UTF-8");//Base64.getEncoder().encodeToString(decryptedKey);
            //System.out.println("RSA Devrypted Key = " + decryptedKeyInString);
            //System.out.println("Size of encrypted String = " + encryptedKeyInString.length());
            String sizeOfEncMessage = String.format("%04d", encMessageInString.length());
            //System.out.println("Size of key = " + encryptedKeyInString.length() + "Size of mac key = " + encryptedMacKeyInString.length() + "Size of tag" + tagInString.length());
            this.body = encryptedKeyInString + "*#*" + tagInString + "*#*"
                    + Base64.getEncoder().encodeToString(siv.getEncoded()) + "*#*" + sizeOfEncMessage + "*#*"
                    + encMessageInString;
            System.out.println("Total message length = " + this.body.length());
        } catch (Exception ex) {
            Logger.getLogger(ClientSendMailLayout.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("\n---------\n" + this.body + "\nlength of message outgoing= "
                + encMessageInString.length() + "\nEncrypted Message: " + encMessageInString); // + "\nDecrypted = " + temp2);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ClientSendMailLayout.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DataLengthException ex) {
        Logger.getLogger(ClientSendMailLayout.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidCipherTextException ex) {
        Logger.getLogger(ClientSendMailLayout.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(ClientSendMailLayout.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (this.toAddress.equals("<enter email address here>")) {
        System.out.println("Please enter a valid email address");
    } else {
        try {
            new SendEmailViaGmail(this.toAddress, this.subject, this.body);
        } catch (IOException ex) {
            Logger.getLogger(ClientSendMailLayout.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.composeWindow.dispatchEvent(new WindowEvent(this.composeWindow, WindowEvent.WINDOW_CLOSING));

    }
}

From source file:emailsecurity.DisplayContentOfEmail.java

public String decryptBodyOfEmail(String incomingMessage)
        throws UnsupportedEncodingException, DataLengthException, InvalidCipherTextException, Exception {
    String body1;/*ww w  .  j av a  2  s.  c  o  m*/
    System.out.println("Incoming message = \n" + incomingMessage + "\nEnd");
    AESBouncyCastle a = new AESBouncyCastle();
    int lengthOfIncoming = incomingMessage.length();
    //System.out.println("Length of message incoming =" + lengthOfIncoming);
    String RSAEncryptedKey = incomingMessage.substring(0, 172);
    System.out.println("1 = " + RSAEncryptedKey);
    //String RSAEncryptedMacKey = incomingMessage.substring(175, 338) + incomingMessage.substring(340, 349);
    //System.out.println("2 = " + RSAEncryptedMacKey);
    //System.out.println("Char at 335 & 336 = " + incomingMessage.charAt(338) + incomingMessage.charAt(339));
    String tagInString = incomingMessage.substring(175, 219);
    System.out.println("3 = " + tagInString);
    String IVInString = incomingMessage.substring(222, 246);//(388, 412);//(175, 199);
    System.out.println("4 = " + IVInString);
    String lengthOfCipherText = incomingMessage.substring(249, 253);//(412, 415);
    System.out.println("5 = " + lengthOfCipherText);
    int lengthOfCipherTextInt = Integer.parseInt(lengthOfCipherText);
    System.out.println("Length of Cipher text= " + lengthOfCipherTextInt);
    String encryptedBodyInString = incomingMessage.substring(256, 256 + lengthOfCipherTextInt);
    System.out.println("6 = " + encryptedBodyInString);
    //String RSAEncryptedMacKey = incomingMessage.substring(212+lengthOfCipherTextInt, 212+lengthOfCipherTextInt+174);
    //System.out.println("Mac Key in String = " + RSAEncryptedMacKey);
    //String tagInString = incomingMessage.substring(212+lengthOfCipherTextInt+174, 212+lengthOfCipherTextInt+174+44);
    //System.out.println("Incoming tag = " + tagInString);
    //System.out.println("Incoming Encrypted Message:" + encryptedBodyInString);
    //System.out.println("IV: " + IVInString);
    //System.out.println("Key: " + keyInString);
    //System.out.println("body: " + encryptedBodyInString);
    byte[] decodedIV = Base64.getDecoder().decode(IVInString);
    SecretKey originalIV = new SecretKeySpec(decodedIV, "AES");
    //PublicKey publicKeyOfReceiver;
    PrivateKey privateKeyOfReceiver;

    //publicKeyOfReceiver = readRSAPublicKey();
    privateKeyOfReceiver = readRSAPrivateKey();
    //String publicKeyString = Base64.getEncoder().encodeToString(publicKeyOfReceiver.getEncoded());//readFileAsString("id_rsa.pub");
    String privateKeyString = Base64.getEncoder().encodeToString(privateKeyOfReceiver.getEncoded());//readFileAsString("id_rsa");
    RSABouncyCastle rsa = new RSABouncyCastle();
    //byte[] decryptedMacKey = rsa.decrypt(Base64.getDecoder().decode(RSAEncryptedMacKey), privateKeyString);
    //String decryptedMacKeyInString = Base64.getEncoder().encodeToString(decryptedMacKey);

    byte[] decryptedKey = rsa.decrypt(Base64.getDecoder().decode(RSAEncryptedKey), privateKeyString);
    String decryptedKeyInString = Base64.getEncoder().encodeToString(decryptedKey);

    byte[] decodedKey = Base64.getDecoder().decode(decryptedKeyInString);
    SecretKey originalKey = new SecretKeySpec(decodedKey, "AES");
    //System.out.println("IV encoded: " + originalIV.getEncoded());
    //System.out.println("Key encoded: " + originalKey.getEncoded());
    a.setKeyAndIV(originalKey.getEncoded(), originalIV.getEncoded());
    byte[] encryptedBodyInBytes = Base64.getDecoder().decode(encryptedBodyInString);
    byte[] decryptedBodyInBytes = a.decrypt(encryptedBodyInBytes);
    String decryptedBodyInString_temp = new String(decryptedBodyInBytes, "UTF-8");
    String macKeyInString = decryptedBodyInString_temp.substring(0, 24);
    String decryptedBodyInString = decryptedBodyInString_temp.substring(24,
            decryptedBodyInString_temp.length());
    System.out.println("--------------");
    System.out.println("decrypted body: " + decryptedBodyInString);
    byte[] macKeyInBytes = Base64.getDecoder().decode(macKeyInString);
    SecretKey macKey = new SecretKeySpec(macKeyInBytes, "AES");
    Digest digest = new SHA256Digest();
    HMac hmac = new HMac(digest);
    hmac.init(new KeyParameter(macKey.getEncoded()));
    hmac.update(Base64.getDecoder().decode(encryptedBodyInString), 0,
            Base64.getDecoder().decode(encryptedBodyInString).length);
    byte[] macTagInBytes = new byte[digest.getDigestSize()];
    hmac.doFinal(macTagInBytes, 0);
    String tagCalculatedInString = Base64.getEncoder().encodeToString(macTagInBytes);
    if (tagInString.equals(tagCalculatedInString)) {
        System.out.println("Tags match!");
    } else {
        System.out.println("Tags don't match!");
    }
    return decryptedBodyInString;
}

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);//from   www  . ja va 2  s  .c  om
    sha256.doFinal(buf, 0);

    return Base32.encode(buf);
}

From source file:freemail.OutboundContact.java

License:Open Source License

private String generateFirstSlot() {
    Logger.minor(this, "Generating first slot for contact");
    SecureRandom rnd = new SecureRandom();
    SHA256Digest sha256 = new SHA256Digest();
    byte[] buf = new byte[sha256.getDigestSize()];

    rnd.nextBytes(buf);/*from w  ww . j a v a  2  s  .c  o m*/

    String firstSlot = Base32.encode(buf);

    this.contactfile.put("nextslot", Base32.encode(buf));

    return firstSlot;
}

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// www  . j  a v  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;
}