org.spongycastle.crypto.params.KeyParameter Java Examples

The following examples show how to use org.spongycastle.crypto.params.KeyParameter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KeyCrypterScrypt.java    From bitherj with Apache License 2.0 6 votes vote down vote up
@Override
public KeyParameter deriveKey(CharSequence password) throws KeyCrypterException {
    byte[] passwordBytes = null;
    try {
        passwordBytes = convertToByteArray(password);
        byte[] salt = new byte[0];
        if (mSalt != null) {
            salt = mSalt;
        } else {
            // Warn the user that they are not using a salt.
            // (Some early MultiBit wallets had a blank salt).
            log.warn("You are using a ScryptParameters with no salt. Your encryption may be vulnerable to a dictionary attack.");
        }

        byte[] keyBytes = SCrypt.scrypt(passwordBytes, salt, BITCOINJ_SCRYPT_N, BITCOINJ_SCRYPT_R, BITCOINJ_SCRYPT_P, KEY_LENGTH);
        return new KeyParameter(keyBytes);
    } catch (Exception e) {
        throw new KeyCrypterException("Could not generate key from password and salt.", e);
    } finally {
        // Zero the password bytes.
        if (passwordBytes != null) {
            java.util.Arrays.fill(passwordBytes, (byte) 0);
        }
    }
}
 
Example #2
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
private Wallet spendUnconfirmedChange(Wallet wallet, Transaction t2, KeyParameter aesKey) throws Exception {
    if (wallet.getTransactionSigners().size() == 1)   // don't bother reconfiguring the p2sh wallet
        wallet = roundTrip(wallet);
    Coin v3 = valueOf(0, 50);
    assertEquals(v3, wallet.getBalance());
    SendRequest req = SendRequest.to(OTHER_ADDRESS, valueOf(0, 48));
    req.aesKey = aesKey;
    req.shuffleOutputs = false;
    wallet.completeTx(req);
    Transaction t3 = req.tx;
    assertNotEquals(t2.getOutput(1).getScriptPubKey().getToAddress(PARAMS),
                    t3.getOutput(1).getScriptPubKey().getToAddress(PARAMS));
    assertNotNull(t3);
    wallet.commitTx(t3);
    assertTrue(wallet.isConsistent());
    // t2 and t3 gets confirmed in the same block.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, t2, t3);
    assertTrue(wallet.isConsistent());
    return wallet;
}
 
Example #3
Source File: BasicKeyChain.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Encrypt the wallet using the KeyCrypter and the AES key. A good default KeyCrypter to use is
 * {@link KeyCrypterScrypt}.
 *
 * @param keyCrypter The KeyCrypter that specifies how to encrypt/ decrypt a key
 * @param aesKey     AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming
 *                   to create from a password)
 * @throws KeyCrypterException Thrown if the wallet encryption fails. If so, the wallet state is unchanged.
 */
@Override
public BasicKeyChain toEncrypted(KeyCrypter keyCrypter, KeyParameter aesKey) {
    lock.lock();
    try {
        checkNotNull(keyCrypter);
        checkState(this.keyCrypter == null, "Key chain is already encrypted");
        BasicKeyChain encrypted = new BasicKeyChain(keyCrypter);
        for (ECKey key : hashToKeys.values()) {
            ECKey encryptedKey = key.encrypt(keyCrypter, aesKey);
            // Check that the encrypted key can be successfully decrypted.
            // This is done as it is a critical failure if the private key cannot be decrypted successfully
            // (all bitcoin controlled by that private key is lost forever).
            // For a correctly constructed keyCrypter the encryption should always be reversible so it is just
            // being as cautious as possible.
            if (!ECKey.encryptionIsReversible(key, encryptedKey, keyCrypter, aesKey))
                throw new KeyCrypterException("The key " + key.toString() + " cannot be successfully decrypted after encryption so aborting wallet encryption.");
            encrypted.importKeyLocked(encryptedKey);
        }
        return encrypted;
    } finally {
        lock.unlock();
    }
}
 
Example #4
Source File: aes.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
public static ByteBuffer decrypt(byte[] key, byte[] iv, byte[] cipertext) {
    try
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] clear = new byte[cipher.getOutputSize(cipertext.length)];
        int len = cipher.processBytes(cipertext, 0, cipertext.length, clear,0);
        len += cipher.doFinal(clear, len);
        ByteBuffer byteBuffer = ByteBuffer.allocate(len);
        byteBuffer.put(clear, 0, len);
        return byteBuffer;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return null;

}
 
Example #5
Source File: aes.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
public static ByteBuffer encrypt(byte[] key, byte[] iv, byte[] plaintext) {
    assert (key.length == 32 && iv.length == 16);
    try
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));

        cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] outBuf   = new byte[cipher.getOutputSize(plaintext.length)];
        int processed = cipher.processBytes(plaintext, 0, plaintext.length, outBuf, 0);
        processed += cipher.doFinal(outBuf, processed);

        ByteBuffer byteBuffer = ByteBuffer.allocate(processed);
        byteBuffer.put(outBuf, 0, processed);
        return byteBuffer;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return null;
}
 
Example #6
Source File: BasicKeyChain.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public BasicKeyChain toDecrypted(KeyParameter aesKey) {
    lock.lock();
    try {
        checkState(keyCrypter != null, "Wallet is already decrypted");
        // Do an up-front check.
        if (numKeys() > 0 && !checkAESKey(aesKey))
            throw new KeyCrypterException("Password/key was incorrect.");
        BasicKeyChain decrypted = new BasicKeyChain();
        for (ECKey key : hashToKeys.values()) {
            decrypted.importKeyLocked(key.decrypt(aesKey));
        }
        return decrypted;
    } finally {
        lock.unlock();
    }
}
 
Example #7
Source File: WalletTool.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
private static void addKey() {
    // If we're being given precise details, we have to import the key.
    if (options.has("privkey") || options.has("pubkey")) {
        importKey();
    } else {
        if (options.has(lookaheadSize)) {
            Integer size = options.valueOf(lookaheadSize);
            log.info("Setting keychain lookahead size to {}", size);
            wallet.setKeyChainGroupLookaheadSize(size);
        }
        ECKey key;
        try {
            key = wallet.freshReceiveKey();
        } catch (DeterministicUpgradeRequiredException e) {
            try {
                KeyParameter aesKey = passwordToKey(false);
                wallet.upgradeToDeterministic(aesKey);
            } catch (DeterministicUpgradeRequiresPassword e2) {
                System.err.println("This wallet must be upgraded to be deterministic, but it's encrypted: please supply the password and try again.");
                return;
            }
            key = wallet.freshReceiveKey();
        }
        System.out.println(key.toAddress(params) + " " + key);
    }
}
 
Example #8
Source File: DeterministicKey.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ECDSASignature sign(Sha256Hash input, @Nullable KeyParameter aesKey) throws KeyCrypterException {
    if (isEncrypted()) {
        // If the key is encrypted, ECKey.sign will decrypt it first before rerunning sign. Decryption walks the
        // key heirarchy to find the private key (see below), so, we can just run the inherited method.
        return super.sign(input, aesKey);
    } else {
        // If it's not encrypted, derive the private via the parents.
        final BigInteger privateKey = findOrDerivePrivateKey();
        if (privateKey == null) {
            // This key is a part of a public-key only heirarchy and cannot be used for signing
            throw new MissingPrivateKeyException();
        }
        return super.doSign(input, privateKey);
    }
}
 
Example #9
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public void emptyWallet(String toAddress,
                        KeyParameter aesKey,
                        ResultHandler resultHandler,
                        ErrorMessageHandler errorMessageHandler)
        throws InsufficientMoneyException, AddressFormatException {
    SendRequest sendRequest = SendRequest.emptyWallet(Address.fromBase58(params, toAddress));
    sendRequest.fee = Coin.ZERO;
    sendRequest.feePerKb = getTxFeeForWithdrawalPerByte().multiply(1000);
    sendRequest.aesKey = aesKey;
    Wallet.SendResult sendResult = wallet.sendCoins(sendRequest);
    printTx("empty wallet", sendResult.tx);
    Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() {
        @Override
        public void onSuccess(Transaction result) {
            log.info("emptyWallet onSuccess Transaction=" + result);
            resultHandler.handleResult();
        }

        @Override
        public void onFailure(@NotNull Throwable t) {
            log.error("emptyWallet onFailure " + t.toString());
            errorMessageHandler.handleErrorMessage(t.getMessage());
        }
    });
}
 
Example #10
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void changeAesKeyTest() {
    Wallet encryptedWallet = new Wallet(PARAMS);
    encryptedWallet.encrypt(PASSWORD1);

    KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter();
    KeyParameter aesKey = keyCrypter.deriveKey(PASSWORD1);

    CharSequence newPassword = "My name is Tom";
    KeyParameter newAesKey = keyCrypter.deriveKey(newPassword);

    encryptedWallet.changeEncryptionKey(keyCrypter, aesKey, newAesKey);

    assertTrue(encryptedWallet.checkAESKey(newAesKey));
    assertFalse(encryptedWallet.checkAESKey(aesKey));
}
 
Example #11
Source File: WalletTool.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
private static void rotate() throws BlockStoreException {
    setup();
    peers.start();
    // Set a key rotation time and possibly broadcast the resulting maintenance transactions.
    long rotationTimeSecs = Utils.currentTimeSeconds();
    if (options.has(dateFlag)) {
        rotationTimeSecs = options.valueOf(dateFlag).getTime() / 1000;
    } else if (options.has(unixtimeFlag)) {
        rotationTimeSecs = options.valueOf(unixtimeFlag);
    }
    log.info("Setting wallet key rotation time to {}", rotationTimeSecs);
    wallet.setKeyRotationTime(rotationTimeSecs);
    KeyParameter aesKey = null;
    if (wallet.isEncrypted()) {
        aesKey = passwordToKey(true);
        if (aesKey == null)
            return;
    }
    Futures.getUnchecked(wallet.doMaintenance(aesKey, true));
}
 
Example #12
Source File: DeterministicKey.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ECDSASignature sign(Sha256Hash input, @Nullable KeyParameter aesKey) throws KeyCrypterException {
    if (isEncrypted()) {
        // If the key is encrypted, ECKey.sign will decrypt it first before rerunning sign. Decryption walks the
        // key heirarchy to find the private key (see below), so, we can just run the inherited method.
        return super.sign(input, aesKey);
    } else {
        // If it's not encrypted, derive the private via the parents.
        final BigInteger privateKey = findOrDerivePrivateKey();
        if (privateKey == null) {
            // This key is a part of a public-key only heirarchy and cannot be used for signing
            throw new MissingPrivateKeyException();
        }
        return super.doSign(input, privateKey);
    }
}
 
Example #13
Source File: SensitiveDataPreApi23.java    From android-java-connect-rest-sample with MIT License 6 votes vote down vote up
protected byte[] encrypt(byte[] data) {
    // 16 bytes is the IV size for AES256
    try {
        SecretKey key = loadKey();

        // Random IV
        SecureRandom rng = new SecureRandom();
        byte[] ivBytes = new byte[16];                                                                  // 16 bytes is the IV size for AES256
        rng.nextBytes(ivBytes);

        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(true, new ParametersWithIV(new KeyParameter(key.getEncoded()), ivBytes));

        byte[] encryptedData = cipherData(cipher, data);
        byte[] encryptedDataWithIV = new byte[encryptedData.length + ivBytes.length];                   // Make room for IV
        System.arraycopy(ivBytes, 0, encryptedDataWithIV, 0, ivBytes.length);                           // Add IV
        System.arraycopy(encryptedData, 0, encryptedDataWithIV, ivBytes.length, encryptedData.length);  // Then the encrypted data
        return encryptedDataWithIV;
    }
    catch(InvalidCipherTextException e) {
        Log.e(TAG, "Can't encrypt data", e);
    }
    return null;
}
 
Example #14
Source File: KeyChainGroupTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void deterministicUpgradeEncrypted() throws Exception {
    group = new KeyChainGroup(PARAMS);
    final ECKey key = new ECKey();
    group.importKeys(key);
    final KeyCrypterScrypt crypter = new KeyCrypterScrypt();
    final KeyParameter aesKey = crypter.deriveKey("abc");
    assertTrue(group.isDeterministicUpgradeRequired());
    group.encrypt(crypter, aesKey);
    assertTrue(group.isDeterministicUpgradeRequired());
    try {
        group.upgradeToDeterministic(0, null);
        fail();
    } catch (DeterministicUpgradeRequiresPassword e) {
        // Expected.
    }
    group.upgradeToDeterministic(0, aesKey);
    assertFalse(group.isDeterministicUpgradeRequired());
    final DeterministicSeed deterministicSeed = group.getActiveKeyChain().getSeed();
    assertNotNull(deterministicSeed);
    assertTrue(deterministicSeed.isEncrypted());
    byte[] entropy = checkNotNull(group.getActiveKeyChain().toDecrypted(aesKey).getSeed()).getEntropyBytes();
    // Check we used the right key: oldest non rotating.
    byte[] truncatedBytes = Arrays.copyOfRange(key.getSecretBytes(), 0, 16);
    assertArrayEquals(entropy, truncatedBytes);
}
 
Example #15
Source File: Address.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public List<byte[]> signHashes(List<byte[]> unsignedInHashes, CharSequence passphrase) throws
        PasswordException {
    ECKey key = PrivateKeyUtil.getECKeyFromSingleString(this.getFullEncryptPrivKey(), passphrase);
    if (key == null) {
        throw new PasswordException("do not decrypt eckey");
    }
    KeyParameter assKey = key.getKeyCrypter().deriveKey(passphrase);
    List<byte[]> result = new ArrayList<byte[]>();
    for (byte[] unsignedInHash : unsignedInHashes) {
        TransactionSignature signature = new TransactionSignature(key.sign(unsignedInHash,
                assKey), TransactionSignature.SigHash.ALL, false);
        result.add(ScriptBuilder.createInputScript(signature, key).getProgram());
    }
    key.clearPrivateKey();
    return result;
}
 
Example #16
Source File: Transaction.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public TransactionSignature calculateWitnessSignature(int inputIndex, ECKey key,
                                                      @Nullable KeyParameter aesKey,
                                                      byte[] redeemScript,
                                                      Coin value,
                                                      SigHash hashType, boolean anyoneCanPay) {
    Sha256Hash hash = hashForSignatureWitness(inputIndex, redeemScript, value, hashType, anyoneCanPay);
    return new TransactionSignature(key.sign(hash, aesKey), hashType, anyoneCanPay);
}
 
Example #17
Source File: BasicKeyChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check whether the AES key can decrypt the first encrypted key in the wallet.
 *
 * @return true if AES key supplied can decrypt the first encrypted private key in the wallet, false otherwise.
 */
@Override
public boolean checkAESKey(KeyParameter aesKey) {
    lock.lock();
    try {
        // If no keys then cannot decrypt.
        if (hashToKeys.isEmpty())
            return false;
        checkState(keyCrypter != null, "Key chain is not encrypted");

        // Find the first encrypted key in the wallet.
        ECKey first = null;
        for (ECKey key : hashToKeys.values()) {
            if (key.isEncrypted()) {
                first = key;
                break;
            }
        }
        checkState(first != null, "No encrypted keys in the wallet");

        try {
            ECKey rebornKey = first.decrypt(aesKey);
            return Arrays.equals(first.getPubKey(), rebornKey.getPubKey());
        } catch (KeyCrypterException e) {
            // The AES key supplied is incorrect.
            return false;
        }
    } finally {
        lock.unlock();
    }
}
 
Example #18
Source File: BasicKeyChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Convenience wrapper around {@link #toEncrypted(KeyCrypter,
 * org.spongycastle.crypto.params.KeyParameter)} which uses the default Scrypt key derivation algorithm and
 * parameters, derives a key from the given password and returns the created key.
 */
@Override
public BasicKeyChain toEncrypted(CharSequence password) {
    checkNotNull(password);
    checkArgument(password.length() > 0);
    KeyCrypter scrypt = new KeyCrypterScrypt();
    KeyParameter derivedKey = scrypt.deriveKey(password);
    return toEncrypted(scrypt, derivedKey);
}
 
Example #19
Source File: WalletPasswordController.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
@FXML
void confirmClicked (ActionEvent event) {
    String password = pass1.getText();
    if (password.isEmpty() || password.length() < 4) {
        informationalAlert("Bad password", "The password you entered is empty or too short.");
        return;
    }

    final KeyCrypterScrypt keyCrypter = (KeyCrypterScrypt) Main.wallet.getKeyCrypter();
    checkNotNull(keyCrypter);   // We should never arrive at this GUI if the wallet isn't actually encrypted.
    KeyDerivationTasks tasks = new KeyDerivationTasks(keyCrypter, password, getTargetTime()) {
        @Override
        protected void onFinish (KeyParameter aesKey, int timeTakenMsec) {
            checkGuiThread();
            if (Main.wallet.checkAESKey(aesKey)) {
                WalletPasswordController.this.aesKey.set(aesKey);
            } else {
                log.warn("User entered incorrect password");
                fadeOut(progressMeter);
                fadeIn(widgetGrid);
                fadeIn(explanationLabel);
                fadeIn(buttonsBox);
                informationalAlert("Wrong password",
                        "Please try entering your password again, carefully checking for typos or spelling errors.");
            }
        }
    };
    progressMeter.progressProperty().bind(tasks.progress);
    tasks.start();

    fadeIn(progressMeter);
    fadeOut(widgetGrid);
    fadeOut(explanationLabel);
    fadeOut(buttonsBox);
}
 
Example #20
Source File: PaymentChannelV1ServerState.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private void signMultisigInput(Transaction tx, Transaction.SigHash hashType,
                               boolean anyoneCanPay, @Nullable KeyParameter userKey) {
    TransactionSignature signature = tx.calculateSignature(0, serverKey, userKey, getContractScript(), hashType, anyoneCanPay);
    byte[] mySig = signature.encodeToBitcoin();
    Script scriptSig = ScriptBuilder.createMultiSigInputScriptBytes(ImmutableList.of(bestValueSignature, mySig));
    tx.getInput(0).setScriptSig(scriptSig);
}
 
Example #21
Source File: MyHMacDSAKCalculator.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
public BigInteger nextK() {
  byte[] t = new byte[((n.bitLength() + 7) / 8)];

  if (needTry) {
    hMac.init(new KeyParameter(K));
    hMac.update(V, 0, V.length);
    hMac.update((byte) 0x00);

    hMac.doFinal(K, 0);

    hMac.init(new KeyParameter(K));

    hMac.update(V, 0, V.length);

    hMac.doFinal(V, 0);
  }

  int tOff = 0;

  while (tOff < t.length) {
    hMac.init(new KeyParameter(K));
    hMac.update(V, 0, V.length);

    hMac.doFinal(V, 0);

    int len = Math.min(t.length - tOff, V.length);
    System.arraycopy(V, 0, t, tOff, len);
    tOff += len;
  }

  BigInteger k = bitsToInt(t);
  needTry = true;
  return k;

}
 
Example #22
Source File: ProfileCipherOutputStream.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public ProfileCipherOutputStream(OutputStream out, byte[] key) throws IOException {
  super(out);
  this.cipher = new GCMBlockCipher(new AESFastEngine());

  byte[] nonce  = generateNonce();
  this.cipher.init(true, new AEADParameters(new KeyParameter(key), 128, nonce));

  super.write(nonce, 0, nonce.length);
}
 
Example #23
Source File: WalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
void encryptWallet(KeyCrypterScrypt keyCrypterScrypt, KeyParameter key) {
    if (this.aesKey != null) {
        log.warn("encryptWallet called but we have a aesKey already set. " +
                "We decryptWallet with the old key before we apply the new key.");
        decryptWallet(this.aesKey);
    }

    wallet.encrypt(keyCrypterScrypt, key);
    aesKey = key;
}
 
Example #24
Source File: KeyChainGroupTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void serialization() throws Exception {
    int initialKeys = INITIAL_KEYS + group.getActiveKeyChain().getAccountPath().size() - 1;
    assertEquals(initialKeys + 1 /* for the seed */, group.serializeToProtobuf().size());
    group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, group.serializeToProtobuf());
    group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicKey key1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicKey key2 = group.freshKey(KeyChain.KeyPurpose.CHANGE);
    group.getBloomFilterElementCount();
    List<Protos.Key> protoKeys1 = group.serializeToProtobuf();
    assertEquals(initialKeys + ((LOOKAHEAD_SIZE + 1) * 2) + 1 /* for the seed */ + 1, protoKeys1.size());
    group.importKeys(new ECKey());
    List<Protos.Key> protoKeys2 = group.serializeToProtobuf();
    assertEquals(initialKeys + ((LOOKAHEAD_SIZE + 1) * 2) + 1 /* for the seed */ + 2, protoKeys2.size());

    group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, protoKeys1);
    assertEquals(initialKeys + ((LOOKAHEAD_SIZE + 1)  * 2)  + 1 /* for the seed */ + 1, protoKeys1.size());
    assertTrue(group.hasKey(key1));
    assertTrue(group.hasKey(key2));
    assertEquals(key2, group.currentKey(KeyChain.KeyPurpose.CHANGE));
    assertEquals(key1, group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS));
    group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, protoKeys2);
    assertEquals(initialKeys + ((LOOKAHEAD_SIZE + 1) * 2) + 1 /* for the seed */ + 2, protoKeys2.size());
    assertTrue(group.hasKey(key1));
    assertTrue(group.hasKey(key2));

    KeyCrypterScrypt scrypt = new KeyCrypterScrypt(2);
    final KeyParameter aesKey = scrypt.deriveKey("password");
    group.encrypt(scrypt, aesKey);
    List<Protos.Key> protoKeys3 = group.serializeToProtobuf();
    group = KeyChainGroup.fromProtobufEncrypted(PARAMS, protoKeys3, scrypt);
    assertTrue(group.isEncrypted());
    assertTrue(group.checkPassword("password"));
    group.decrypt(aesKey);

    // No need for extensive contents testing here, as that's done in the keychain class tests.
}
 
Example #25
Source File: SecureUtils.java    From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static byte[] decryptCCM(@NonNull final byte[] data,
                                @NonNull final byte[] key,
                                @NonNull final byte[] nonce,
                                @NonNull final byte[] additionalData,
                                final int micSize) throws InvalidCipherTextException {
    final byte[] ccm = new byte[data.length - micSize];

    final CCMBlockCipher ccmBlockCipher = new CCMBlockCipher(new AESEngine());
    final AEADParameters aeadParameters = new AEADParameters(new KeyParameter(key), micSize * 8, nonce, additionalData);
    ccmBlockCipher.init(false, aeadParameters);
    ccmBlockCipher.processBytes(data, 0, data.length, ccm, 0);
    ccmBlockCipher.doFinal(ccm, 0);
    return ccm;
}
 
Example #26
Source File: KeyChainGroupTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void encryptionWhilstEmpty() throws Exception {
    group = new KeyChainGroup(PARAMS);
    group.setLookaheadSize(5);
    KeyCrypterScrypt scrypt = new KeyCrypterScrypt(2);
    final KeyParameter aesKey = scrypt.deriveKey("password");
    group.encrypt(scrypt, aesKey);
    assertTrue(group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).isEncrypted());
    final ECKey key = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    group.decrypt(aesKey);
    assertFalse(checkNotNull(group.findKeyFromPubKey(key.getPubKey())).isEncrypted());
}
 
Example #27
Source File: LWallet.java    From dapp-wallet-demo with Apache License 2.0 5 votes vote down vote up
private static byte[] generateAes128CtrDerivedKey(
        byte[] password, byte[] salt, int c, String prf) throws CipherException {

    if (!prf.equals("hmac-sha256")) {
        throw new CipherException("Unsupported prf:" + prf);
    }

    // Java 8 supports this, but you have to convert the password to a character array, see
    // http://stackoverflow.com/a/27928435/3211687

    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
    gen.init(password, salt, c);
    return ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
}
 
Example #28
Source File: KeyCrypterScrypt.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generate AES key.
 *
 * This is a very slow operation compared to encrypt/ decrypt so it is normally worth caching the result.
 *
 * @param password    The password to use in key generation
 * @return            The KeyParameter containing the created AES key
 * @throws            KeyCrypterException
 */
@Override
public KeyParameter deriveKey(CharSequence password) throws KeyCrypterException {
    byte[] passwordBytes = null;
    try {
        passwordBytes = convertToByteArray(password);
        byte[] salt = new byte[0];
        if ( scryptParameters.getSalt() != null) {
            salt = scryptParameters.getSalt().toByteArray();
        } else {
            // Warn the user that they are not using a salt.
            // (Some early MultiBit wallets had a blank salt).
            log.warn("You are using a ScryptParameters with no salt. Your encryption may be vulnerable to a dictionary attack.");
        }

        final Stopwatch watch = Stopwatch.createStarted();
        byte[] keyBytes = SCrypt.scrypt(passwordBytes, salt, (int) scryptParameters.getN(), scryptParameters.getR(), scryptParameters.getP(), KEY_LENGTH);
        watch.stop();
        log.info("Deriving key took {} for {} scrypt iterations.", watch, scryptParameters.getN());
        return new KeyParameter(keyBytes);
    } catch (Exception e) {
        throw new KeyCrypterException("Could not generate key from password and salt.", e);
    } finally {
        // Zero the password bytes.
        if (passwordBytes != null) {
            java.util.Arrays.fill(passwordBytes, (byte) 0);
        }
    }
}
 
Example #29
Source File: DeterministicKeyChain.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean checkAESKey(KeyParameter aesKey) {
    checkState(rootKey != null, "Can't check password for a watching chain");
    checkNotNull(aesKey);
    checkState(getKeyCrypter() != null, "Key chain not encrypted");
    try {
        return rootKey.decrypt(aesKey).getPubKeyPoint().equals(rootKey.getPubKeyPoint());
    } catch (KeyCrypterException e) {
        return false;
    }
}
 
Example #30
Source File: DeterministicKeyChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public DeterministicKeyChain toDecrypted(CharSequence password) {
    checkNotNull(password);
    checkArgument(password.length() > 0);
    KeyCrypter crypter = getKeyCrypter();
    checkState(crypter != null, "Chain not encrypted");
    KeyParameter derivedKey = crypter.deriveKey(password);
    return toDecrypted(derivedKey);
}