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: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.  ja  v  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;
    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;
}

From source file:net.sourceforge.keepassj2me.datasource.HTTPConnectionThread.java

License:Open Source License

/**
 * Generate key from encryption code by running SHA256 multiple rounds
 * @param encCode String with code//from  w  w w.j  a v a 2  s  .  c  o m
 * @return String with encrypted code
 */
private byte[] passwordKeySHA(String encCode) {
    byte[] encBytes = encCode.getBytes();
    for (int i = 0; i < encBytes.length; i++)
        encBytes[i] -= '0';

    byte[] encKey;

    SHA256Digest md = new SHA256Digest();
    encKey = new byte[md.getDigestSize()];

    // #ifdef DEBUG
    System.out.println("encBytes: " + new String(Hex.encode(encBytes)));
    // #endif
    md.update(encBytes, 0, encBytes.length);
    md.doFinal(encKey, 0);

    for (int i = 0; i < HTTPConnectionThread.PASSWORD_KEY_SHA_ROUNDS - 1; i++) {
        md.reset();
        md.update(encKey, 0, encKey.length);
        md.doFinal(encKey, 0);
    }

    // #ifdef DEBUG
    System.out.println("encKey: " + new String(Hex.encode(encKey)));
    // #endif

    return encKey;
}

From source file:net.sourceforge.keepassj2me.importerv3.ImporterV3.java

License:Open Source License

/**
 * Load a v3 database file, return contents in a new PwManager.
 * //from  w w w  . ja  va 2s. c  o  m
 * @param infile  Existing file to load.
 * @param password Pass phrase for infile.
 * @param pRepair (unused)
 * @return new PwManager container.
 * 
 * @throws IOException on any file error.
 * @throws InvalidKeyException on a decryption error, or possible internal bug.
 * @throws IllegalBlockSizeException on a decryption error, or possible internal bug.
 * @throws BadPaddingException on a decryption error, or possible internal bug.
 * @throws NoSuchAlgorithmException on a decryption error, or possible internal bug.
 * @throws NoSuchPaddingException on a decryption error, or possible internal bug.
 * @throws InvalidAlgorithmParameterException if error decrypting main file body. 
 * @throws ShortBufferException if error decrypting main file body.
 */
public PwManager openDatabase(InputStream inStream, String password)
        throws IOException, InvalidCipherTextException, Exception {
    PwManager newManager;
    SHA256Digest md;
    /** Master key encrypted several times */
    byte[] transformedMasterKey;
    byte[] finalKey;

    setProgress(5, "Open database");
    // #ifdef DEBUG
    System.out.println("Open database");
    // #endif

    // Load entire file, most of it's encrypted.
    // InputStream in = new FileInputStream( infile );
    byte[] filebuf = new byte[(int) inStream.available()];
    inStream.read(filebuf, 0, (int) inStream.available());
    inStream.close();

    // Parse header (unencrypted)
    if (filebuf.length < PwDbHeader.BUF_SIZE)
        throw new IOException("File too short for header");
    PwDbHeader hdr = new PwDbHeader(filebuf, 0);

    if ((hdr.signature1 != PwManager.PWM_DBSIG_1) || (hdr.signature2 != PwManager.PWM_DBSIG_2)) {
        // #ifdef DEBUG
        System.out.println("Bad database file signature");
        // #endif
        throw new IOException("Bad database file signature");
    }

    if (hdr.version != PwManager.PWM_DBVER_DW) {
        // #ifdef DEBUG
        System.out.println("Bad database file version");
        // #endif
        throw new IOException("Bad database file version");
    }

    newManager = new PwManager();
    newManager.setMasterKey(password);

    // Select algorithm
    if ((hdr.flags & PwManager.PWM_FLAG_RIJNDAEL) != 0) {
        // #ifdef DEBUG
        System.out.println("Algorithm AES");
        // #endif
        newManager.algorithm = PwManager.ALGO_AES;
    } else if ((hdr.flags & PwManager.PWM_FLAG_TWOFISH) != 0) {
        // #ifdef DEBUG
        System.out.println("Algorithm TWOFISH");
        // #endif
        newManager.algorithm = PwManager.ALGO_TWOFISH;
    } else {
        throw new IOException("Unknown algorithm.");
    }

    if (newManager.algorithm == PwManager.ALGO_TWOFISH)
        throw new IOException("TwoFish algorithm is not supported");

    newManager.numKeyEncRounds = hdr.numKeyEncRounds;
    // #ifdef DEBUG
    System.out.println("rounds = " + newManager.numKeyEncRounds);
    // #endif

    // testRijndael_JCE();

    newManager.name = "KeePass Password Manager";

    // Generate transformedMasterKey from masterKey
    //KeePassMIDlet.logS ("masterSeed2: " + new String(Hex.encode(hdr.masterSeed2)));

    setProgress(10, "Decrypt key");
    transformedMasterKey = transformMasterKey(hdr.masterSeed2, newManager.masterKey,
            newManager.numKeyEncRounds);
    // Hash the master password with the salt in the file
    md = new SHA256Digest();
    md.update(hdr.masterSeed, 0, hdr.masterSeed.length);
    md.update(transformedMasterKey, 0, transformedMasterKey.length);
    finalKey = new byte[md.getDigestSize()];
    md.doFinal(finalKey, 0);

    setProgress(90, "Decrypt database");

    // NI
    //KeePassMIDlet.logS ("finalKey: " + new String(Hex.encode(finalKey)));

    // Initialize Rijndael algorithm

    // Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5Padding" );
    //PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
    BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine()));

    //cipher.init( Cipher.DECRYPT_MODE, new SecretKeySpec( finalKey, "AES" ), new IvParameterSpec( hdr.encryptionIV ) );

    cipher.init(false, new ParametersWithIV(new KeyParameter(finalKey), hdr.encryptionIV));
    // Decrypt! The first bytes aren't encrypted (that's the header)
    //int encryptedPartSize = cipher.doFinal( filebuf, PwDbHeader.BUF_SIZE, filebuf.length - PwDbHeader.BUF_SIZE, filebuf, PwDbHeader.BUF_SIZE );
    //int encryptedPartSize
    int paddedEncryptedPartSize = cipher.processBytes(filebuf, PwDbHeader.BUF_SIZE,
            filebuf.length - PwDbHeader.BUF_SIZE, filebuf, PwDbHeader.BUF_SIZE);

    int encryptedPartSize = 0;
    //try {
    PKCS7Padding padding = new PKCS7Padding();
    encryptedPartSize = paddedEncryptedPartSize - padding.padCount(filebuf);
    //} catch (Exception e) {
    //}
    // NI
    byte[] plainContent = new byte[encryptedPartSize];
    System.arraycopy(filebuf, PwDbHeader.BUF_SIZE, plainContent, 0, encryptedPartSize);
    // #ifdef DEBUG
    System.out.println("filebuf length: " + filebuf.length);
    // #endif
    //System.out.println ("file length: " + filebuf.length);
    //System.out.println ("plaintext contents length: " + encryptedPartSize);
    //System.out.println ("plaintext contents:\n" + new String(Hex.encode(plainContent)));

    //if( pRepair == null ) {
    //md = MessageDigest.getInstance( "SHA-256" );
    md = new SHA256Digest();
    md.update(filebuf, PwDbHeader.BUF_SIZE, encryptedPartSize);
    //      md.update( makePad(filebuf) );
    md.doFinal(finalKey, 0);

    if (Util.compare(finalKey, hdr.contentsHash) == false) {
        //KeePassMIDlet.logS ( "Database file did not decrypt correctly. (checksum code is broken)" );
        // #ifdef DEBUG
        System.out.println("Database file did not decrypt correctly. (checksum code is broken)");
        // #endif
        throw new Exception(
                "Wrong Password, or Database File Corrupted (database file did not decrypt correctly)");
    }
    // }

    setProgress(95, "Import groups");
    // Import all groups
    // #ifdef DEBUG
    System.out.println("Import all groups");
    // #endif

    int pos = PwDbHeader.BUF_SIZE;
    PwGroup newGrp = new PwGroup();
    for (int i = 0; i < hdr.numGroups;) {
        int fieldType = Types.readShort(filebuf, pos);
        pos += 2;
        int fieldSize = Types.readInt(filebuf, pos);
        pos += 4;

        if (fieldType == 0xFFFF) {
            // #ifdef DEBUG
            System.out.println(newGrp.level + " " + newGrp.name);
            // #endif

            // End-Group record.  Save group and count it.
            //newManager.groups.add( newGrp );
            newManager.addGroup(newGrp);
            newGrp = new PwGroup();
            i++;
        } else {
            readGroupField(newGrp, fieldType, filebuf, pos);
        }
        pos += fieldSize;
    }

    //    fixGroups( groups );

    setProgress(97, "Import entries");
    // Import all entries
    // #ifdef DEBUG
    System.out.println("Import all entries");
    // #endif

    PwEntry newEnt = new PwEntry();
    for (int i = 0; i < hdr.numEntries;) {
        int fieldType = Types.readShort(filebuf, pos);
        int fieldSize = Types.readInt(filebuf, pos + 2);

        if (fieldType == 0xFFFF) {
            // End-Group record.  Save group and count it.
            newManager.addEntry(newEnt);
            // #ifdef DEBUG
            System.out.println(newEnt.title);
            // #endif
            newEnt = new PwEntry();
            i++;
        } else {
            readEntryField(newEnt, filebuf, pos);
        }
        pos += 2 + 4 + fieldSize;
    }

    // Keep the Meta-Info entry separate
    // #ifdef DEBUG
    System.out.println("Keep the Meta-Info entry separate");
    // #endif

    for (int i = 0; i < newManager.entries.size(); i++) {
        PwEntry ent = (PwEntry) newManager.entries.elementAt(i);
        if (ent.title.equals("Meta-Info") && ent.url.equals("$") && ent.username.equals("SYSTEM")) {
            newManager.metaInfo = ent;
            newManager.entries.removeElementAt(i);
        }
    }

    setProgress(100, "Done");
    // #ifdef DEBUG
    System.out.println("Return newManager: " + newManager);
    // #endif

    return newManager;
}

From source file:net.sourceforge.keepassj2me.importerv3.ImporterV3.java

License:Open Source License

/**
 * Encrypt the master key a few times to make brute-force key-search harder
 * @throws NoSuchPaddingException //from   ww  w.  j a  va  2 s .  c  om
 * @throws NoSuchAlgorithmException 
 * @throws ShortBufferException
 */

private byte[] transformMasterKey(byte[] pKeySeed, byte[] pKey, int rounds)
/*throws InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException,
NoSuchAlgorithmException,
NoSuchPaddingException, ShortBufferException*/ {
    // #ifdef DEBUG
    System.out.println("transformMasterKey, rounds=" + rounds);
    System.out.println("transformMasterKey, pkey=" + new String(Hex.encode(pKey)));
    // #endif

    byte[] newKey = new byte[pKey.length];
    int i;

    BufferedBlockCipher cipher = new BufferedBlockCipher(new AESEngine());
    cipher.init(true, new KeyParameter(pKeySeed));

    int procent = 10; //10% - progress start
    int step = 5;//% step
    int roundsByStep = rounds * step / ((90 - procent)); //90% - progress end
    int count = 0;

    newKey = pKey;
    for (i = 0; i < rounds; i++) {
        cipher.processBytes(newKey, 0, newKey.length, newKey, 0);

        if (++count == roundsByStep) {
            count = 0;
            setProgress(procent += step, null);
        }
    }
    // Hash once with SHA-256
    SHA256Digest md = new SHA256Digest();
    md.update(newKey, 0, newKey.length);
    //newKey = md.digest( newKey );
    md.doFinal(newKey, 0);

    return newKey;
}

From source file:net.sourceforge.keepassj2me.importerv3.PwManager.java

License:Open Source License

public void setMasterKey(String key) {
    if (key == null || key.length() == 0)
        throw new IllegalArgumentException("Key cannot be empty.");

    SHA256Digest md = new SHA256Digest();
    md.update(key.getBytes(), 0, key.getBytes().length);
    masterKey = new byte[md.getDigestSize()];
    md.doFinal(masterKey, 0);/*from w  ww  .j av a 2 s  .  co  m*/
}

From source file:net.sourceforge.keepassj2me.keydb.KeydbUtil.java

License:Open Source License

/**
 * hash data from input stream//from   ww w .j av a2 s  .c om
 * @param is input stream
 * @param size data size or -1
 * @return hash
 * @throws KeydbException
 */
public static byte[] hash(InputStream is, int size) throws KeydbException {
    try {
        byte[] buf;
        if (size == -1)
            size = is.available();

        switch (size) {
        case 0:
            throw new KeydbException(Config.getLocaleString(keys.KD_KEYFILE_EMPTY));
        case 32:
            buf = new byte[32];
            is.read(buf, 0, 32);
            return buf;
        case 64:
            buf = new byte[64];
            is.read(buf, 0, 64);
            try {
                checkHex(buf);
                return Hex.decode(buf);
            } catch (Exception e) {
                return hash(buf);
            }
        default:
            buf = new byte[4096];
            SHA256Digest digest = new SHA256Digest();
            while (size > 0) {
                int len = (size > buf.length ? buf.length : size);
                is.read(buf, 0, len);
                digest.update(buf, 0, len);
                size -= len;
            }
            ;
            byte[] hash = new byte[digest.getDigestSize()];
            digest.doFinal(hash, 0);
            return hash;
        }
    } catch (IOException e) {
        throw new KeydbException(Config.getLocaleString(keys.KD_KEYFILE_READ_ERR));
    }
}

From source file:net.sourceforge.keepassj2me.keydb.KeydbUtil.java

License:Open Source License

/**
 * Get hash of binary chanks/* w w w . jav a 2  s.  c  o  m*/
 * @param bufs
 * @return hash
 */
public static byte[] hash(byte[][] bufs) {
    SHA256Digest digest = new SHA256Digest();
    for (int i = 0; i < bufs.length; ++i)
        digest.update(bufs[i], 0, bufs[i].length);
    byte[] hash = new byte[digest.getDigestSize()];
    digest.doFinal(hash, 0);
    return hash;
}

From source file:net.sourceforge.keepassj2me.keydb.KeydbUtil.java

License:Open Source License

/**
 * Get hash of buffer part/*from   w  w  w. j  a va2  s . co m*/
 * @param buf
 * @param offset
 * @param length
 * @return hash
 */
public static byte[] hash(byte[] buf, int offset, int length) {
    SHA256Digest digest = new SHA256Digest();
    digest.update(buf, offset, length);
    byte[] hash = new byte[digest.getDigestSize()];
    digest.doFinal(hash, 0);
    return hash;
}

From source file:no.digipost.api.client.filters.response.ResponseContentSHA256Filter.java

License:Apache License

private void validerBytesMotHashHeader(final String serverHash, final byte[] entityBytes) {
    SHA256Digest digest = new SHA256Digest();

    digest.update(entityBytes, 0, entityBytes.length);
    byte[] result = new byte[digest.getDigestSize()];
    digest.doFinal(result, 0);/*from  www. j  a  v  a  2  s  . c  o m*/
    String ourHash = new String(Base64.encode(result));
    if (!serverHash.equals(ourHash)) {
        throw new DigipostClientException(SERVER_SIGNATURE_ERROR,
                "X-Content-SHA256-header matchet ikke innholdet - server-signatur er feil.");
    }
}

From source file:org.cryptoworkshop.ximix.common.crypto.ECDecryptionProof.java

License:Apache License

private void addIn(SHA256Digest sha256, ECPoint point) {
    byte[] enc = point.getEncoded(true);

    sha256.update(enc, 0, enc.length);
}