public static ArrayList<byte[]> createReqSmsMessage(Contact contact)
      throws FailedToSendSessionRequestException {
    final int MAX_REQUEST_LENGTH = 256;
    final int REQUEST_SMS_LENGTH = 128;

    try {
      byte[] request = SessionManager.generateSessionRequest(contact);

      if (request.length != MAX_REQUEST_LENGTH)
        throw new FailedToSendSessionRequestException("Request length is not standard");

      byte[] firstMessage = Arrays.copyOfRange(request, 0, REQUEST_SMS_LENGTH);
      byte[] secondMessage = Arrays.copyOfRange(request, REQUEST_SMS_LENGTH, request.length);

      byte[] firstType = new byte[1];
      firstType[0] = (byte) SmsMessage.Type.RequestFirstSMS.ordinal();
      byte[] secondType = new byte[1];
      secondType[0] = (byte) SmsMessage.Type.RequestSecondSMS.ordinal();

      ArrayList<byte[]> partialRequests = new ArrayList<byte[]>(2);
      partialRequests.add(Arrays.concatenate(firstType, firstMessage));
      partialRequests.add(Arrays.concatenate(secondType, secondMessage));

      return partialRequests;

    } catch (FailedToGenerateSessionRequestException e) {
      throw new FailedToSendSessionRequestException("Failed to send the session request sms");
    }
  }
 private void ˏ(
     int paramInt, int[] paramArrayOfInt1, int[] paramArrayOfInt2, int[] paramArrayOfInt3) {
   int i = 1;
   String str = "";
   this.beO = paramInt;
   if ((this.beO == paramArrayOfInt2.length) && (this.beO == paramArrayOfInt1.length)) {
     paramInt = i;
     if (this.beO == paramArrayOfInt3.length) {}
   } else {
     paramInt = 0;
     str = "Unexpected parameterset format";
   }
   i = 0;
   while (i < this.beO) {
     if ((paramArrayOfInt3[i] < 2) || ((paramArrayOfInt1[i] - paramArrayOfInt3[i]) % 2 != 0)) {
       paramInt = 0;
       str = "Wrong parameter K (K >= 2 and H-K even required)!";
     }
     if ((paramArrayOfInt1[i] < 4) || (paramArrayOfInt2[i] < 2)) {
       paramInt = 0;
       str = "Wrong parameter H or w (H > 3 and w > 1 required)!";
     }
     i += 1;
   }
   if (paramInt != 0) {
     this.beC = Arrays.י(paramArrayOfInt1);
     this.beP = Arrays.י(paramArrayOfInt2);
     this.aGN = Arrays.י(paramArrayOfInt3);
     return;
   }
   throw new IllegalArgumentException(str);
 }
Exemple #3
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");
    }
  }
 @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);
 }
  @Test
  public void deterministicUpgradeUnencrypted() throws Exception {
    // Check that a group that contains only random keys has its HD chain created using the private
    // key bytes of
    // the oldest random key, so upgrading the same wallet twice gives the same outcome.
    group = new KeyChainGroup(params);
    group.setLookaheadSize(LOOKAHEAD_SIZE); // Don't want slow tests.
    ECKey key1 = new ECKey();
    Utils.rollMockClock(86400);
    ECKey key2 = new ECKey();
    group.importKeys(key2, key1);

    List<Protos.Key> protobufs = group.serializeToProtobuf();
    group.upgradeToDeterministic(0, null);
    assertFalse(group.isDeterministicUpgradeRequired());
    DeterministicKey dkey1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicSeed seed1 = group.getActiveKeyChain().getSeed();
    assertNotNull(seed1);

    group = KeyChainGroup.fromProtobufUnencrypted(params, protobufs);
    group.upgradeToDeterministic(0, null); // Should give same result as last time.
    DeterministicKey dkey2 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicSeed seed2 = group.getActiveKeyChain().getSeed();
    assertEquals(seed1, seed2);
    assertEquals(dkey1, dkey2);

    // Check we used the right (oldest) key despite backwards import order.
    byte[] truncatedBytes = Arrays.copyOfRange(key1.getSecretBytes(), 0, 16);
    assertArrayEquals(seed1.getEntropyBytes(), truncatedBytes);
  }
  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 static byte[] createAckSmsMessage(Contact contact)
      throws FailedToSendSessionAcknowledgeException {
    try {
      byte[] ack = SessionManager.generateSessionAcknowledge(contact);
      byte[] type = new byte[1];
      type[0] = (byte) SmsMessage.Type.Acknowledge.ordinal();
      return Arrays.concatenate(type, ack);

    } catch (FailedToAcknowledgeSessionException e) {
      throw new FailedToSendSessionAcknowledgeException("Failed to respond to the session request");
    }
  }
 static byte[][] ˊ(byte[][] paramArrayOfByte) {
   if (paramArrayOfByte == null) {
     return null;
   }
   byte[][] arrayOfByte = new byte[paramArrayOfByte.length][];
   int i = 0;
   while (i != paramArrayOfByte.length) {
     arrayOfByte[i] = Arrays.І(paramArrayOfByte[i]);
     i += 1;
   }
   return arrayOfByte;
 }
 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))));
 }
Exemple #10
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;
    }
Exemple #11
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");
    }
  }
 @Test
 public void deterministicUpgradeRotating() throws Exception {
   group = new KeyChainGroup(params);
   group.setLookaheadSize(LOOKAHEAD_SIZE); // Don't want slow tests.
   long now = Utils.currentTimeSeconds();
   ECKey key1 = new ECKey();
   Utils.rollMockClock(86400);
   ECKey key2 = new ECKey();
   Utils.rollMockClock(86400);
   ECKey key3 = new ECKey();
   group.importKeys(key2, key1, key3);
   group.upgradeToDeterministic(now + 10, null);
   DeterministicSeed seed = group.getActiveKeyChain().getSeed();
   assertNotNull(seed);
   // Check we used the right key: oldest non rotating.
   byte[] truncatedBytes = Arrays.copyOfRange(key2.getSecretBytes(), 0, 16);
   assertArrayEquals(seed.getEntropyBytes(), truncatedBytes);
 }
  /**
   * return true if the internal state represents the signature described in the passed in array.
   */
  public boolean verifySignature(byte[] signature) {
    if (forSigning) {
      throw new IllegalStateException("RSADigestSigner not initialised for verification");
    }

    byte[] hash = new byte[digest.getDigestSize()];

    digest.doFinal(hash, 0);

    byte[] sig;
    byte[] expected;

    try {
      sig = rsaEngine.processBlock(signature, 0, signature.length);
      expected = derEncode(hash);
    } catch (Exception e) {
      return false;
    }

    if (sig.length == expected.length) {
      return Arrays.constantTimeAreEqual(sig, expected);
    } else if (sig.length == expected.length - 2) // NULL left out
    {
      int sigOffset = sig.length - hash.length - 2;
      int expectedOffset = expected.length - hash.length - 2;

      expected[1] -= 2; // adjust lengths
      expected[3] -= 2;

      int nonEqual = 0;

      for (int i = 0; i < hash.length; i++) {
        nonEqual |= (sig[sigOffset + i] ^ expected[expectedOffset + i]);
      }

      for (int i = 0; i < sigOffset; i++) {
        nonEqual |= (sig[i] ^ expected[i]); // check header less NULL
      }

      return nonEqual == 0;
    } else {
      return false;
    }
  }
Exemple #14
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");
      }
    }
Exemple #15
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)));
    }
  }
Exemple #16
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");
    }
  }
 public int[] qQ() {
   return Arrays.י(this.aGN);
 }
 public int[] qO() {
   return Arrays.י(this.beC);
 }
 public int[] qP() {
   return Arrays.י(this.beP);
 }
 /** Returns a copy of the output detached from its containing transaction, if need be. */
 public TransactionOutput duplicateDetached() {
   return new TransactionOutput(
       params, null, Coin.valueOf(value), org.spongycastle.util.Arrays.clone(scriptBytes));
 }
Exemple #21
0
 public Apdu(byte[] apdu, int length) {
   this(Arrays.copyOf(apdu, length));
 }
 public byte[] rb() {
   return Arrays.І(this.bfp);
 }
Exemple #23
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");
      }
    }
Exemple #24
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");
  }
 /**
  * Obtains the value of the {@link #PARAM_TYPE_KEY key parameter}, or <code>null</code> if not
  * set.
  */
 public byte[] getKey() {
   return Arrays.clone((byte[]) parameters.get(Integers.valueOf(PARAM_TYPE_KEY)));
 }
 /**
  * Obtains the value of the {@link #PARAM_TYPE_NONCE nonce parameter}, or <code>null</code> if not
  * set.
  */
 public byte[] getNonce() {
   return Arrays.clone((byte[]) parameters.get(Integers.valueOf(PARAM_TYPE_NONCE)));
 }
  /** 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());
              }
            }
          }
        });
  }
 /**
  * Obtains the value of the {@link #PARAM_TYPE_PERSONALISATION personalisation parameter}, or
  * <code>null</code> if not set.
  */
 public byte[] getPersonalisation() {
   return Arrays.clone((byte[]) parameters.get(Integers.valueOf(PARAM_TYPE_PERSONALISATION)));
 }
 /**
  * Obtains the value of the {@link #PARAM_TYPE_KEY_IDENTIFIER key identifier parameter}, or <code>
  * null</code> if not set.
  */
 public byte[] getKeyIdentifier() {
   return Arrays.clone((byte[]) parameters.get(Integers.valueOf(PARAM_TYPE_KEY_IDENTIFIER)));
 }
Exemple #30
0
 public Object clone() {
   return new IntArray(Arrays.clone(m_ints));
 }