List of usage examples for org.bouncycastle.crypto.digests SHA256Digest getDigestSize
public int getDigestSize()
From source file:dorkbox.util.Sys.java
License:Apache License
/** * gets the SHA256 hash + SALT of the specified username, as UTF-16 *///from w ww. ja v a 2 s.c om 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 *///from ww w . j a v a 2s . c om 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.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);/*ww w . j a v a 2 s. c om*/ 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//from ww w. j av a 2s. co m */ 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 . j a v a2 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; }/*from w w w. ja v a2 s . c o 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; }
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 ww . j av a2 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.j av a 2 s . 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.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);// w ww.j a v a 2 s .co m }
From source file:net.sourceforge.keepassj2me.keydb.KeydbUtil.java
License:Open Source License
/** * hash data from input stream//from w ww .j a v a 2 s.co m * @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)); } }