List of usage examples for org.bouncycastle.crypto.digests SHA256Digest doFinal
public int doFinal(byte[] out, int outOff)
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 2s. co 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 /* w w w . jav a2 s .c o m*/ * @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 source file:net.sourceforge.keepassj2me.keydb.KeydbUtil.java
License:Open Source License
/** * hash data from input stream//w w w . j a v a 2 s . c o 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)); } }
From source file:net.sourceforge.keepassj2me.keydb.KeydbUtil.java
License:Open Source License
/** * Get hash of binary chanks//from www . java 2 s . co 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/* ww w . j a va 2s . c om*/ * @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); 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 w ww .j ava 2s . c o m }
From source file:org.cryptoworkshop.ximix.common.crypto.ECDecryptionProof.java
License:Apache License
private BigInteger computeChallenge(ECPoint a, ECPoint b, ECPoint c, ECPoint partial, ECPoint g, ECPoint q) { SHA256Digest sha256 = new SHA256Digest(); addIn(sha256, a);/*from w w w. ja v a 2 s . c o m*/ addIn(sha256, b); addIn(sha256, c); addIn(sha256, partial); addIn(sha256, g); addIn(sha256, q); byte[] res = new byte[sha256.getDigestSize()]; sha256.doFinal(res, 0); return new BigInteger(1, res); }
From source file:org.cryptoworkshop.ximix.demo.client.Main.java
License:Apache License
public static void main(String[] args) throws Exception { XimixRegistrar registrar = XimixRegistrarFactory.createServicesRegistrar(new File(args[0]), new EventNotifier() { @Override//from w w w .ja v a2s . c o m public void notify(Level level, Throwable throwable) { System.err.print(level + " " + throwable.getMessage()); throwable.printStackTrace(System.err); } @Override public void notify(Level level, Object detail) { System.err.println(level + " " + detail.toString()); } @Override public void notify(Level level, Object detail, Throwable throwable) { System.err.println(level + " " + detail.toString()); throwable.printStackTrace(System.err); } }); KeyService keyFetcher = registrar.connect(KeyService.class); //UploadService client = registrar.connect(UploadService.class); SigningService signingService = registrar.connect(SigningService.class); byte[] encPubKey = keyFetcher.fetchPublicKey("ECENCKEY"); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.createKey(encPubKey); ECElGamalEncryptor encryptor = new ECElGamalEncryptor(); encryptor.init(pubKey); ECPoint candidate1 = generatePoint(pubKey.getParameters(), new SecureRandom()); ECPoint candidate2 = generatePoint(pubKey.getParameters(), new SecureRandom()); // // encrypt two candidate numbers // ECPair encCandidate1 = encryptor.encrypt(candidate1); ECPair encCandidate2 = encryptor.encrypt(candidate2); PairSequence ballot = new PairSequence(encCandidate1, encCandidate2); // client.uploadMessage("FRED", ballot.getEncoded()); SHA256Digest sha256 = new SHA256Digest(); byte[] message = ballot.getEncoded(); byte[] hash = new byte[sha256.getDigestSize()]; sha256.update(message, 0, message.length); sha256.doFinal(hash, 0); // // ECDSA // SignatureGenerationOptions sigGenOptions = new SignatureGenerationOptions.Builder(Algorithm.ECDSA) .withThreshold(2).withNodes("A", "B", "C", "D").build(); byte[] dsaSig = signingService.generateSignature("ECSIGKEY", sigGenOptions, hash); // // check the signature locally. // ECDSASigner signer = new ECDSASigner(); ECPublicKeyParameters sigPubKey = (ECPublicKeyParameters) PublicKeyFactory .createKey(signingService.fetchPublicKey("ECSIGKEY")); signer.init(false, sigPubKey); BigInteger[] rs = decodeSig(dsaSig); if (signer.verifySignature(hash, rs[0], rs[1])) { System.out.println("sig verified!"); } else { System.out.println("sig failed..."); } SignatureGenerationOptions blsSigGenOptions = new SignatureGenerationOptions.Builder(Algorithm.BLS) .withThreshold(3).withNodes("B", "C", "D").build(); byte[] blsSig = signingService.generateSignature("BLSSIGKEY", blsSigGenOptions, hash); // // check the signature locally. // BLS01Signer blsSigner = new BLS01Signer(sha256); BLS01PublicKeyParameters blsPubKey = BLSPublicKeyFactory .createKey(signingService.fetchPublicKey("BLSSIGKEY")); blsSigner.init(false, blsPubKey); blsSigner.update(message, 0, message.length); if (blsSigner.verifySignature(blsSig)) { System.out.println("sig verified!"); } else { System.out.println("sig failed..."); } keyFetcher.shutdown(); signingService.shutdown(); registrar.shutdown(); }