Example #1
0
  private void testCipherNameWithWrap(String name, String simpleName) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(new SecureRandom());
    SecretKey key = kg.generateKey();

    byte[] salt = {
      (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
      (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99
    };
    char[] password = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};

    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFac = SecretKeyFactory.getInstance(name);
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
    Cipher pbeEncryptCipher = Cipher.getInstance(name, "SC");

    pbeEncryptCipher.init(Cipher.WRAP_MODE, pbeKey, pbeParamSpec);

    byte[] symKeyBytes = pbeEncryptCipher.wrap(key);

    Cipher simpleCipher = Cipher.getInstance(simpleName, "SC");

    simpleCipher.init(Cipher.UNWRAP_MODE, pbeKey, pbeParamSpec);

    SecretKey unwrappedKey = (SecretKey) simpleCipher.unwrap(symKeyBytes, "AES", Cipher.SECRET_KEY);

    if (!Arrays.areEqual(unwrappedKey.getEncoded(), key.getEncoded())) {
      fail("key mismatch on unwrapping");
    }
  }
  private static void compareKO(
      String name, Properties config, int test, byte[] calculatedOKM, byte[] testOKM) {

    if (!Arrays.areEqual(calculatedOKM, testOKM)) {
      throw new TestFailedException(
          new SimpleTestResult(false, name + " using " + config + " test " + test + " failed"));
    }
  }
 public void testSamples() throws IOException {
   assertTrue(Arrays.areEqual(sample1Bytes, UrlBase64.decode(sample1)));
   assertTrue(Arrays.areEqual(sample1Bytes, UrlBase64.decode(Strings.toByteArray(sample1))));
   assertTrue(Arrays.areEqual(sample2Bytes, UrlBase64.decode(sample2)));
   assertTrue(Arrays.areEqual(sample2Bytes, UrlBase64.decode(Strings.toByteArray(sample2))));
   assertTrue(Arrays.areEqual(sample3Bytes, UrlBase64.decode(sample3)));
   assertTrue(Arrays.areEqual(sample3Bytes, UrlBase64.decode(Strings.toByteArray(sample3))));
 }
Example #4
0
    private AlgorithmParameters checkParameters(Cipher c, byte[] salt, int iCount)
        throws InvalidParameterSpecException {
      AlgorithmParameters param = c.getParameters();
      PBEParameterSpec spec = (PBEParameterSpec) param.getParameterSpec(PBEParameterSpec.class);

      if (!Arrays.areEqual(salt, spec.getSalt())) {
        fail("" + algorithm + "failed salt test");
      }

      if (iCount != spec.getIterationCount()) {
        fail("" + algorithm + "failed count test");
      }
      return param;
    }
Example #5
0
  private void rawModeTest(
      String sigName,
      DERObjectIdentifier digestOID,
      PrivateKey privKey,
      PublicKey pubKey,
      SecureRandom random)
      throws Exception {
    byte[] sampleMessage = new byte[1000 + random.nextInt(100)];
    random.nextBytes(sampleMessage);

    Signature normalSig = Signature.getInstance(sigName, "SC");

    PSSParameterSpec spec =
        (PSSParameterSpec) normalSig.getParameters().getParameterSpec(PSSParameterSpec.class);

    // Make sure we generate the same 'random' salt for both normal and raw signers
    int saltLen = spec.getSaltLength();
    byte[] fixedRandomBytes = new byte[saltLen];
    random.nextBytes(fixedRandomBytes);

    normalSig.initSign(privKey, new FixedSecureRandom(fixedRandomBytes));
    normalSig.update(sampleMessage);
    byte[] normalResult = normalSig.sign();

    MessageDigest digest = MessageDigest.getInstance(digestOID.getId(), "SC");
    byte[] hash = digest.digest(sampleMessage);

    Signature rawSig = Signature.getInstance("RAWRSASSA-PSS", "SC");

    // Need to init the params explicitly to avoid having a 'raw' variety of every PSS algorithm
    rawSig.setParameter(spec);

    rawSig.initSign(privKey, new FixedSecureRandom(fixedRandomBytes));
    rawSig.update(hash);
    byte[] rawResult = rawSig.sign();

    if (!Arrays.areEqual(normalResult, rawResult)) {
      fail("raw mode signature differs from normal one");
    }

    rawSig.initVerify(pubKey);
    rawSig.update(hash);

    if (!rawSig.verify(rawResult)) {
      fail("raw mode signature verification failed");
    }
  }
Example #6
0
    public void performTest() throws Exception {
      byte[] salt = new byte[16];
      int iCount = 100;

      for (int i = 0; i != salt.length; i++) {
        salt[i] = (byte) i;
      }

      OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();

      pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(password), salt, iCount);

      ParametersWithIV params = (ParametersWithIV) pGen.generateDerivedParameters(keySize, ivSize);

      SecretKeySpec encKey =
          new SecretKeySpec(((KeyParameter) params.getParameters()).getKey(), baseAlgorithm);

      Cipher c;

      if (baseAlgorithm.equals("RC4")) {
        c = Cipher.getInstance(baseAlgorithm, "SC");

        c.init(Cipher.ENCRYPT_MODE, encKey);
      } else {
        c = Cipher.getInstance(baseAlgorithm + "/CBC/PKCS7Padding", "SC");

        c.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV()));
      }

      byte[] enc = c.doFinal(salt);

      c = Cipher.getInstance(algorithm, "SC");

      PBEKeySpec keySpec = new PBEKeySpec(password, salt, iCount);
      SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm, "SC");

      c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec));

      byte[] dec = c.doFinal(enc);

      if (!Arrays.areEqual(salt, dec)) {
        fail("" + algorithm + "failed encryption/decryption test");
      }
    }
Example #7
0
  public void testPBEonSecretKeyHmac(String hmacName, byte[] output) {
    SecretKey key;
    byte[] out;
    Mac mac;

    try {
      SecretKeyFactory fact = SecretKeyFactory.getInstance(hmacName, "SC");

      key = fact.generateSecret(new PBEKeySpec("hello".toCharArray(), new byte[20], 100, 160));

      mac = Mac.getInstance("HMAC-SHA1", "SC");
    } catch (Exception e) {
      fail("Failed - exception " + e.toString(), e);
      return;
    }

    try {
      mac.init(key);
    } catch (Exception e) {
      fail("Failed - exception " + e.toString(), e);
      return;
    }

    mac.reset();

    mac.update(message, 0, message.length);

    out = mac.doFinal();

    if (!Arrays.areEqual(out, output)) {
      fail(
          "Failed - expected "
              + new String(Hex.encode(output))
              + " got "
              + new String(Hex.encode(out)));
    }
  }
Example #8
0
  private void checkPBE(String baseAlg, boolean defIsUTF8, String utf8, String eightBit)
      throws Exception {
    byte[] utf8K = Hex.decode(utf8);
    byte[] ascK = Hex.decode(eightBit);

    SecretKeyFactory f = SecretKeyFactory.getInstance(baseAlg, "SC");
    KeySpec ks1 = new PBEKeySpec("\u0141\u0142".toCharArray(), new byte[20], 4096, 160);
    if (!Arrays.areEqual((defIsUTF8) ? utf8K : ascK, f.generateSecret(ks1).getEncoded())) {
      fail(
          baseAlg
              + " wrong PBKDF2 k1 key generated, got : "
              + new String(Hex.encode(f.generateSecret(ks1).getEncoded())));
    }

    KeySpec ks2 = new PBEKeySpec("\u0041\u0042".toCharArray(), new byte[20], 4096, 160);
    if (!Arrays.areEqual(ascK, f.generateSecret(ks2).getEncoded())) {
      fail(baseAlg + " wrong PBKDF2 k2 key generated");
    }
    f = SecretKeyFactory.getInstance(baseAlg + "AndUTF8", "SC");
    ks1 = new PBEKeySpec("\u0141\u0142".toCharArray(), new byte[20], 4096, 160);
    if (!Arrays.areEqual(utf8K, f.generateSecret(ks1).getEncoded())) {
      fail(baseAlg + " wrong PBKDF2 k1 utf8 key generated");
    }

    ks2 = new PBEKeySpec("\u0041\u0042".toCharArray(), new byte[20], 4096, 160);
    if (!Arrays.areEqual(ascK, f.generateSecret(ks2).getEncoded())) {
      fail(baseAlg + " wrong PBKDF2 k2 utf8 key generated");
    }
    f = SecretKeyFactory.getInstance(baseAlg + "And8BIT", "SC");
    ks1 = new PBEKeySpec("\u0141\u0142".toCharArray(), new byte[20], 4096, 160);
    if (!Arrays.areEqual(ascK, f.generateSecret(ks1).getEncoded())) {
      fail(baseAlg + " wrong PBKDF2 k1 8bit key generated");
    }

    ks2 = new PBEKeySpec("\u0041\u0042".toCharArray(), new byte[20], 4096, 160);
    if (!Arrays.areEqual(ascK, f.generateSecret(ks2).getEncoded())) {
      fail(baseAlg + " wrong PBKDF2 k2 8bit key generated");
    }
  }
  /** Change the wallet password. */
  @Override
  public void actionPerformed(ActionEvent e) {
    changePasswordPanel.clearMessages();
    privateKeysBackupFile = null;

    char[] newPasswordToUse = null;
    char[] currentPasswordToUse = null;

    if (currentPassword.getPassword() == null || currentPassword.getPassword().length == 0) {
      // Notify must enter the current password.
      changePasswordPanel.setMessage1(
          controller.getLocaliser().getString("changePasswordPanel.enterCurrentPassword"));
      return;
    }
    currentPasswordToUse = currentPassword.getPassword();

    // Get the new passwords on the password fields.
    if (newPassword.getPassword() == null || newPassword.getPassword().length == 0) {
      // Notify the user must enter a new password.
      changePasswordPanel.setMessage1(
          controller.getLocaliser().getString("changePasswordPanel.enterPasswords"));
      return;
    } else {
      if (!Arrays.areEqual(newPassword.getPassword(), repeatNewPassword.getPassword())) {
        // Notify user passwords are different.
        changePasswordPanel.setMessage1(
            controller
                .getLocaliser()
                .getString("showExportPrivateKeysAction.passwordsAreDifferent"));
        return;
      } else {
        newPasswordToUse = newPassword.getPassword();
      }
    }

    Wallet wallet = super.fastcoinController.getModel().getActiveWallet();
    if (wallet != null) {
      // Double check wallet is not busy then declare that the active
      // wallet is busy with the task.
      WalletData perWalletModelData =
          super.fastcoinController.getModel().getActivePerWalletModelData();

      if (!perWalletModelData.isBusy()) {
        perWalletModelData.setBusy(true);
        perWalletModelData.setBusyTaskKey("changePasswordSubmitAction.text");

        super.fastcoinController.fireWalletBusyChange(true);

        boolean decryptSuccess = false;
        KeyCrypter keyCrypterToUse = wallet.getKeyCrypter();
        try {
          wallet.decrypt(keyCrypterToUse.deriveKey(CharBuffer.wrap(currentPasswordToUse)));
          decryptSuccess = true;
        } catch (KeyCrypterException kce) {
          // Notify the user that the decrypt failed.
          changePasswordPanel.setMessage1(
              controller
                  .getLocaliser()
                  .getString(
                      "changePasswordPanel.changePasswordFailed", new String[] {kce.getMessage()}));

          // Declare that wallet is no longer busy with the task.
          perWalletModelData.setBusyTaskKey(null);
          perWalletModelData.setBusy(false);
          super.fastcoinController.fireWalletBusyChange(false);

          return;
        }

        if (decryptSuccess) {
          try {
            wallet.encrypt(
                keyCrypterToUse, keyCrypterToUse.deriveKey(CharBuffer.wrap(newPasswordToUse)));
            FileHandler fileHandler = new FileHandler(super.fastcoinController);
            fileHandler.savePerWalletModelData(
                super.fastcoinController.getModel().getActivePerWalletModelData(), true);

            // Backup the private keys.
            privateKeysBackupFile =
                fileHandler.backupPrivateKeys(CharBuffer.wrap(newPasswordToUse));

            // Backup the wallet and wallet info
            BackupManager.INSTANCE.backupPerWalletModelData(fileHandler, perWalletModelData);
          } catch (KeyCrypterException kce) {
            // Notify the user that the encrypt failed.
            changePasswordPanel.setMessage1(
                controller
                    .getLocaliser()
                    .getString(
                        "changePasswordPanel.changePasswordFailed",
                        new String[] {kce.getMessage()}));
            return;
          } catch (IOException ede) {
            // Notify the user that the private key backup failed.
            changePasswordPanel.setMessage2(
                controller
                    .getLocaliser()
                    .getString(
                        "changePasswordPanel.keysBackupFailed", new String[] {ede.getMessage()}));
            return;
          } finally {
            // Declare that wallet is no longer busy with the task.
            perWalletModelData.setBusyTaskKey(null);
            perWalletModelData.setBusy(false);
            super.fastcoinController.fireWalletBusyChange(false);
          }
        } else {
          // Declare that wallet is no longer busy with the task.
          perWalletModelData.setBusyTaskKey(null);
          perWalletModelData.setBusy(false);
          super.fastcoinController.fireWalletBusyChange(false);
        }
      }
    }

    // Success.
    SwingUtilities.invokeLater(
        new Runnable() {
          @Override
          public void run() {
            changePasswordPanel.clearMessages();
            changePasswordPanel.clearPasswords();
            changePasswordPanel.setMessage1(
                controller.getLocaliser().getString("changePasswordPanel.changePasswordSuccess"));
            if (privateKeysBackupFile != null) {
              try {
                changePasswordPanel.setMessage2(
                    controller.getLocaliser().getString("changePasswordPanel.oldBackupsMessage"));
                changePasswordPanel.setMessage3(
                    controller
                        .getLocaliser()
                        .getString(
                            "changePasswordPanel.keysBackupSuccess",
                            new Object[] {privateKeysBackupFile.getCanonicalPath()}));
              } catch (IOException e1) {
                log.debug(e1.getClass().getCanonicalName() + " " + e1.getMessage());
              }
            }
          }
        });
  }
Example #10
0
  public void performTest() throws Exception {
    byte[] input = Hex.decode("1234567890abcdefabcdef1234567890fedbca098765");

    //
    // DES
    //
    Cipher cEnc = Cipher.getInstance("DES/CBC/PKCS7Padding", "SC");

    cEnc.init(
        Cipher.ENCRYPT_MODE,
        new SecretKeySpec(Hex.decode("30e69252758e5346"), "DES"),
        new IvParameterSpec(Hex.decode("7c1c1ab9c454a688")));

    byte[] out = cEnc.doFinal(input);

    char[] password = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};

    Cipher cDec =
        makePBECipherUsingParam(
            "PBEWithSHA1AndDES",
            Cipher.DECRYPT_MODE,
            password,
            Hex.decode("7d60435f02e9e0ae"),
            2048);

    byte[] in = cDec.doFinal(out);

    if (!Arrays.areEqual(input, in)) {
      fail("DES failed");
    }

    cDec =
        makePBECipherWithoutParam(
            "PBEWithSHA1AndDES",
            Cipher.DECRYPT_MODE,
            password,
            Hex.decode("7d60435f02e9e0ae"),
            2048);

    in = cDec.doFinal(out);

    if (!Arrays.areEqual(input, in)) {
      fail("DES failed without param");
    }

    //
    // DESede
    //
    cEnc = Cipher.getInstance("DESede/CBC/PKCS7Padding", "SC");

    cEnc.init(
        Cipher.ENCRYPT_MODE,
        new SecretKeySpec(Hex.decode("732f2d33c801732b7206756cbd44f9c1c103ddd97c7cbe8e"), "DES"),
        new IvParameterSpec(Hex.decode("b07bf522c8d608b8")));

    out = cEnc.doFinal(input);

    cDec =
        makePBECipherUsingParam(
            "PBEWithSHAAnd3-KeyTripleDES-CBC",
            Cipher.DECRYPT_MODE,
            password,
            Hex.decode("7d60435f02e9e0ae"),
            2048);

    in = cDec.doFinal(out);

    if (!Arrays.areEqual(input, in)) {
      fail("DESede failed");
    }

    //
    // 40Bit RC2
    //
    cEnc = Cipher.getInstance("RC2/CBC/PKCS7Padding", "SC");

    cEnc.init(
        Cipher.ENCRYPT_MODE,
        new SecretKeySpec(Hex.decode("732f2d33c8"), "RC2"),
        new IvParameterSpec(Hex.decode("b07bf522c8d608b8")));

    out = cEnc.doFinal(input);

    cDec =
        makePBECipherUsingParam(
            "PBEWithSHAAnd40BitRC2-CBC",
            Cipher.DECRYPT_MODE,
            password,
            Hex.decode("7d60435f02e9e0ae"),
            2048);

    in = cDec.doFinal(out);

    if (!Arrays.areEqual(input, in)) {
      fail("RC2 failed");
    }

    //
    // 128bit RC4
    //
    cEnc = Cipher.getInstance("RC4", "SC");

    cEnc.init(
        Cipher.ENCRYPT_MODE,
        new SecretKeySpec(Hex.decode("732f2d33c801732b7206756cbd44f9c1"), "RC4"));

    out = cEnc.doFinal(input);

    cDec =
        makePBECipherUsingParam(
            "PBEWithSHAAnd128BitRC4",
            Cipher.DECRYPT_MODE,
            password,
            Hex.decode("7d60435f02e9e0ae"),
            2048);

    in = cDec.doFinal(out);

    if (!Arrays.areEqual(input, in)) {
      fail("RC4 failed");
    }

    cDec =
        makePBECipherWithoutParam(
            "PBEWithSHAAnd128BitRC4",
            Cipher.DECRYPT_MODE,
            password,
            Hex.decode("7d60435f02e9e0ae"),
            2048);

    in = cDec.doFinal(out);

    if (!Arrays.areEqual(input, in)) {
      fail("RC4 failed without param");
    }

    for (int i = 0; i != pkcs12Tests.length; i++) {
      pkcs12Tests[i].perform();
    }

    for (int i = 0; i != openSSLTests.length; i++) {
      openSSLTests[i].perform();
    }

    testPBEHMac("PBEWithHMacSHA1", hMac1);
    testPBEHMac("PBEWithHMacRIPEMD160", hMac2);

    testPBEonSecretKeyHmac("PBKDF2WithHmacSHA1", hMac3);

    testCipherNameWithWrap("PBEWITHSHA256AND128BITAES-CBC-BC", "AES/CBC/PKCS5Padding");
    testCipherNameWithWrap("PBEWITHSHAAND40BITRC4", "RC4");
    testCipherNameWithWrap("PBEWITHSHAAND128BITRC4", "RC4");

    checkPBE(
        "PBKDF2WithHmacSHA1",
        true,
        "f14687fc31a66e2f7cc01d0a65f687961bd27e20",
        "6f6579193d6433a3e4600b243bb390674f04a615");
  }
Example #11
0
    public void performTest() throws Exception {
      byte[] salt = new byte[digest.getDigestSize()];
      int iCount = 100;

      digest.doFinal(salt, 0);

      PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(digest);

      pGen.init(PBEParametersGenerator.PKCS12PasswordToBytes(password), salt, iCount);

      ParametersWithIV params = (ParametersWithIV) pGen.generateDerivedParameters(keySize, ivSize);

      SecretKeySpec encKey =
          new SecretKeySpec(((KeyParameter) params.getParameters()).getKey(), baseAlgorithm);

      Cipher c;

      if (baseAlgorithm.equals("RC4")) {
        c = Cipher.getInstance(baseAlgorithm, "SC");

        c.init(Cipher.ENCRYPT_MODE, encKey);
      } else {
        c = Cipher.getInstance(baseAlgorithm + "/CBC/PKCS7Padding", "SC");

        c.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV()));
      }

      byte[] enc = c.doFinal(salt);

      c = Cipher.getInstance(algorithm, "SC");

      PBEKeySpec keySpec = new PBEKeySpec(password, salt, iCount);
      SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm, "SC");

      c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec));

      byte[] dec = c.doFinal(enc);

      if (!Arrays.areEqual(salt, dec)) {
        fail("" + algorithm + "failed encryption/decryption test");
      }

      //
      // get the parameters
      //
      AlgorithmParameters param = checkParameters(c, salt, iCount);

      //
      // try using parameters
      //
      c = Cipher.getInstance(algorithm, "SC");

      keySpec = new PBEKeySpec(password);

      c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec), param);

      checkParameters(c, salt, iCount);

      dec = c.doFinal(enc);

      if (!Arrays.areEqual(salt, dec)) {
        fail("" + algorithm + "failed encryption/decryption test");
      }

      //
      // try using PBESpec
      //
      c = Cipher.getInstance(algorithm, "SC");

      keySpec = new PBEKeySpec(password);

      c.init(
          Cipher.DECRYPT_MODE,
          fact.generateSecret(keySpec),
          param.getParameterSpec(PBEParameterSpec.class));

      checkParameters(c, salt, iCount);

      dec = c.doFinal(enc);

      if (!Arrays.areEqual(salt, dec)) {
        fail("" + algorithm + "failed encryption/decryption test");
      }
    }