public static String printKeyHash(Activity context) {
    PackageInfo packageInfo;
    String key = null;
    try {
      // getting application package name, as defined in manifest
      String packageName = context.getApplicationContext().getPackageName();

      // Retriving package info
      packageInfo =
          context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);

      Log.e("Package Name=", context.getApplicationContext().getPackageName());

      for (Signature signature : packageInfo.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        key = new String(Base64.encode(md.digest(), 0));

        // String key = new String(Base64.encodeBytes(md.digest()));
        Log.e("Key Hash=", key);
      }
    } catch (PackageManager.NameNotFoundException e1) {
      Log.e("Name not found", e1.toString());
    } catch (NoSuchAlgorithmException e) {
      Log.e("No such an algorithm", e.toString());
    } catch (Exception e) {
      Log.e("Exception", e.toString());
    }

    return key;
  }
Пример #2
0
  /**
   * (non-Javadoc)
   *
   * @see co.innovate.rentavoz.seguridad.EncoderManager#encodeMd5Hash(java.lang.String)
   */
  @Override
  public String encodeMd5Hash(String input) {
    String md5 = null;

    if (null == input) {
      return null;
    }

    try {

      // Create MessageDigest object for MD5
      MessageDigest digest = MessageDigest.getInstance(MD52);

      // Update input string in message digest
      digest.update(input.getBytes(), 0, input.length());

      // Converts message digest value in base 16 (hex)
      md5 = new BigInteger(1, digest.digest()).toString(SIZE_BUFFERING);

    } catch (NoSuchAlgorithmException e) {

      logEncoderManager.error(e.toString());
    }
    return md5;
  }
 /** Initalizes a new BDecoder. Nothing is read from the given <code>InputStream</code> yet. */
 public BDecoder(InputStream in) {
   this.in = in;
   // XXX - Used for ugly hack.
   try {
     sha_digest = MessageDigest.getInstance("SHA");
   } catch (NoSuchAlgorithmException nsa) {
     throw new InternalError(nsa.toString());
   }
 }
Пример #4
0
  public static byte[] getDigest(byte[] message) {
    if (md == null) {
      try {
        md = MessageDigest.getInstance("MD5");
      } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException((e.toString()));
      }
    }

    return md.digest(message);
  }
Пример #5
0
 public static final byte[] digestBytes(byte[] data) throws RuntimeException {
   synchronized (Md5Encoder.class) {
     if (md5 == null) {
       try {
         md5 = MessageDigest.getInstance("MD5");
       } catch (NoSuchAlgorithmException e) {
         throw new RuntimeException(e.toString());
       }
     }
     return md5.digest(data);
   }
 }
Пример #6
0
 /*
  * Given a string, this method converts to an SHA hash
  */
 public static String SHA(String s) {
   try {
     s = saltPrefix + s + saltPostfix;
     MessageDigest md = MessageDigest.getInstance("SHA");
     md.update(s.getBytes(), 0, s.getBytes().length);
     byte[] hash = md.digest();
     return hexToString(hash);
   } catch (NoSuchAlgorithmException e) {
     log.error(e.toString());
     return null;
   }
 }
Пример #7
0
  private static MessageDigest getInstance() {

    if (INSTANCE == null) {
      try {
        INSTANCE = MessageDigest.getInstance("MD5");
      } catch (final NoSuchAlgorithmException anE) {
        BasicLogger.error(anE.toString());
      }
    }

    return INSTANCE;
  }
Пример #8
0
  private void initGlobal() {
    boolean globalInitDone = false;

    if (!globalInitDone) {
      try {
        ctx = SSLContext.getInstance("TLS");
      } catch (NoSuchAlgorithmException e) {
        throw new Exception(e.toString());
      }

      globalInitDone = true;
    }
  }
  public void openConnection() throws IOException {
    try {
      connectionFactory.useSslProtocol();
    } catch (NoSuchAlgorithmException ex) {
      throw new IOException(ex.toString());
    } catch (KeyManagementException ex) {
      throw new IOException(ex.toString());
    }

    if (connection == null) {
      connection = connectionFactory.newConnection();
    }
  }
Пример #10
0
 public PrivateKey readKey(String name) throws IOException {
   RSAPrivateCrtKeySpec sp = readKeyFile(name);
   KeyFactory kf;
   try {
     kf = KeyFactory.getInstance("RSA");
   } catch (NoSuchAlgorithmException e) {
     throw new IOException("RSA: " + e.toString());
   }
   PrivateKey pk;
   try {
     pk = kf.generatePrivate(sp);
   } catch (InvalidKeySpecException e) {
     throw new IOException(e.toString());
   }
   return pk;
 }
  /*
   * Constructs (i.e., parses) an <code>EncryptedPrivateKeyInfo</code> from
   * its ASN.1 encoding.
   *
   * @param encoded the ASN.1 encoding of this object.
   * @exception NullPointerException if the <code>encoded</code> is null.
   * @exception IOException if error occurs when parsing the ASN.1 encoding.
   */
  public EncryptedPrivateKeyInfo(byte[] encoded) throws NullPointerException, IOException {
    if (encoded == null) {
      throw new NullPointerException("parameters null");
    }

    ByteArrayInputStream bIn = new ByteArrayInputStream(encoded);
    ASN1InputStream dIn = new ASN1InputStream(bIn);

    infoObj =
        new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo((ASN1Sequence) dIn.readObject());

    try {
      algP = this.getParameters();
    } catch (NoSuchAlgorithmException e) {
      throw new IOException("can't create parameters: " + e.toString());
    }
  }
Пример #12
0
  /**
   * generate an X509 CRL, based on the current issuer and subject, using the passed in provider for
   * the signing.
   */
  public X509CRL generateX509CRL(PrivateKey key, String provider, SecureRandom random)
      throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException {
    Signature sig = null;

    try {
      sig = Signature.getInstance(sigOID.getId(), provider);
    } catch (NoSuchAlgorithmException ex) {
      try {
        sig = Signature.getInstance(signatureAlgorithm, provider);
      } catch (NoSuchAlgorithmException e) {
        throw new SecurityException("exception creating signature: " + e.toString());
      }
    }

    if (random != null) {
      sig.initSign(key, random);
    } else {
      sig.initSign(key);
    }

    if (extensions != null) {
      tbsGen.setExtensions(new X509Extensions(extOrdering, extensions));
    }

    TBSCertList tbsCrl = tbsGen.generateTBSCertList();

    try {
      ByteArrayOutputStream bOut = new ByteArrayOutputStream();
      DEROutputStream dOut = new DEROutputStream(bOut);

      dOut.writeObject(tbsCrl);

      sig.update(bOut.toByteArray());
    } catch (Exception e) {
      throw new SecurityException("exception encoding TBS cert - " + e);
    }

    // Construct the CRL
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCrl);
    v.add(sigAlgId);
    v.add(new DERBitString(sig.sign()));

    return new X509CRLObject(new CertificateList(new DERSequence(v)));
  }
Пример #13
0
 /*
  * Needs to be deterministic and not change between Nuxeo EP releases. Turns "field_with_too_many_chars_for_oracle"
  * into "FIELD_WITH_TOO_MANY_C_58557BA3".
  */
 protected String makeName(String name, int maxNameSize) {
   if (name.length() > maxNameSize) {
     MessageDigest digest;
     try {
       digest = MessageDigest.getInstance("MD5");
     } catch (NoSuchAlgorithmException e) {
       throw new RuntimeException(e.toString(), e);
     }
     byte[] bytes = name.getBytes();
     digest.update(bytes, 0, bytes.length);
     name = name.substring(0, maxNameSize - 1 - 8);
     name += '_' + toHexString(digest.digest()).substring(0, 8);
   }
   name = storesUpperCaseIdentifiers() ? name.toUpperCase() : name.toLowerCase();
   name = name.replace(':', '_');
   return name;
 }
Пример #14
0
  /**
   * Compute the hash an IP address. The hash is the first 8 bytes of the SHA digest of the IP
   * address.
   */
  private static byte[] computeAddressHash() {

    /*
     * Get the local host's IP address.
     */
    byte[] addr =
        (byte[])
            java.security.AccessController.doPrivileged(
                new PrivilegedAction() {
                  public Object run() {
                    try {
                      return InetAddress.getLocalHost().getAddress();
                    } catch (Exception e) {
                    }
                    return new byte[] {0, 0, 0, 0};
                  }
                });

    byte[] addrHash;
    final int ADDR_HASH_LENGTH = 8;

    try {
      /*
       * Calculate message digest of IP address using SHA.
       */
      MessageDigest md = MessageDigest.getInstance("SHA");
      ByteArrayOutputStream sink = new ByteArrayOutputStream(64);
      DataOutputStream out = new DataOutputStream(new DigestOutputStream(sink, md));
      out.write(addr, 0, addr.length);
      out.flush();

      byte digest[] = md.digest();
      int hashlength = Math.min(ADDR_HASH_LENGTH, digest.length);
      addrHash = new byte[hashlength];
      System.arraycopy(digest, 0, addrHash, 0, hashlength);

    } catch (IOException ignore) {
      /* can't happen, but be deterministic anyway. */
      addrHash = new byte[0];
    } catch (NoSuchAlgorithmException complain) {
      throw new InternalError(complain.toString());
    }
    return addrHash;
  }
Пример #15
0
  /**
   * Generate the RSA key pairs for encrypting the DES file key
   *
   * @throws InvalidKeySpecException
   */
  private void genRSAKeys() throws InvalidKeySpecException {
    try {
      KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");

      SecureRandom random = new SecureRandom();
      String seed = ((Long) System.currentTimeMillis()).toString();
      random.setSeed(seed.getBytes());
      keygen.initialize(1024, random);

      KeyPair kp = keygen.generateKeyPair();
      publicKey = (RSAPublicKey) kp.getPublic();
      privateKey = (RSAPrivateKey) kp.getPrivate();

      // System.out.println("RSA public key: " + publicKey);
      // System.out.println("RSA private key: " + privateKey);

    } catch (NoSuchAlgorithmException e) {
      System.out.println("Failed to generate RSA key pairs!\n" + e.toString());
    }
  }
Пример #16
0
 @Override
 public void listen(String host, int port, int backlog, TLSParams tls) {
   SSLContext ssl = null;
   if (tls != null) {
     try {
       ssl = makeSSLContext(tls);
     } catch (NoSuchAlgorithmException e) {
       throw new EvaluatorException(e.toString());
     } catch (KeyManagementException e) {
       throw new EvaluatorException(e.toString());
     }
   }
   log.debug("About to listen for HTTP on {}:{}", host, port);
   if (ssl != null) {
     log.debug("Using SSLContext " + ssl);
   }
   try {
     server = NettyFactory.get().createServer(port, host, backlog, makePipeline(tls, ssl));
     log.debug("Listening on port {}", port);
   } catch (ChannelException ce) {
     stub.onError(ce.getMessage());
     stub.onClose(null, null);
   }
 }
    public String getBase64EncryptedElementSignature() {
      // Step 0: construct the text of the elements in elementSignatureSource (done)
      // 		Where...
      //      * Elements are separated by newline characters.
      //      * Filename is the unencrypted filename (no .enc suffix).
      //      * Md5 hashes of the unencrypted files' contents are converted
      //        to zero-padded 32-character strings before concatenation.
      //      Assumes this is in the order:
      //			formId
      //			version   (omitted if null)
      //			base64RsaEncryptedSymmetricKey
      //			instanceId
      //          for each media file { filename "::" md5Hash }
      //          submission.xml "::" md5Hash

      // Step 1: construct the (raw) md5 hash of Step 0.
      byte[] messageDigest;
      try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(elementSignatureSource.toString().getBytes(UTF_8));
        messageDigest = md.digest();
      } catch (NoSuchAlgorithmException e) {
        Log.e(t, e.toString());
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      } catch (UnsupportedEncodingException e) {
        Log.e(t, e.toString());
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      }

      // Step 2: construct the base64-encoded RSA-encrypted md5
      try {
        Cipher pkCipher;
        pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM);
        // write AES key
        pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
        byte[] pkEncryptedKey = pkCipher.doFinal(messageDigest);
        return wrapper.encodeToString(pkEncryptedKey);

      } catch (NoSuchAlgorithmException e) {
        Log.e(t, "Unable to encrypt the symmetric key");
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      } catch (NoSuchPaddingException e) {
        Log.e(t, "Unable to encrypt the symmetric key");
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      } catch (InvalidKeyException e) {
        Log.e(t, "Unable to encrypt the symmetric key");
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      } catch (IllegalBlockSizeException e) {
        Log.e(t, "Unable to encrypt the symmetric key");
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      } catch (BadPaddingException e) {
        Log.e(t, "Unable to encrypt the symmetric key");
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      }
    }
    EncryptedFormInformation(
        String formId,
        String formVersion,
        FormController.InstanceMetadata instanceMetadata,
        PublicKey rsaPublicKey,
        Base64Wrapper wrapper) {
      this.formId = formId;
      this.formVersion = formVersion;
      this.instanceMetadata = instanceMetadata;
      this.rsaPublicKey = rsaPublicKey;
      this.wrapper = wrapper;

      // generate the symmetric key from random bits...

      SecureRandom r = new SecureRandom();
      byte[] key = new byte[SYMMETRIC_KEY_LENGTH / 8];
      r.nextBytes(key);
      SecretKeySpec sk = new SecretKeySpec(key, SYMMETRIC_ALGORITHM);
      symmetricKey = sk;

      // construct the fixed portion of the iv -- the ivSeedArray
      // this is the md5 hash of the instanceID and the symmetric key
      try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(instanceMetadata.instanceId.getBytes(UTF_8));
        md.update(key);
        byte[] messageDigest = md.digest();
        ivSeedArray = new byte[IV_BYTE_LENGTH];
        for (int i = 0; i < IV_BYTE_LENGTH; ++i) {
          ivSeedArray[i] = messageDigest[(i % messageDigest.length)];
        }
      } catch (NoSuchAlgorithmException e) {
        Log.e(t, e.toString());
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      } catch (UnsupportedEncodingException e) {
        Log.e(t, e.toString());
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      }

      // construct the base64-encoded RSA-encrypted symmetric key
      try {
        Cipher pkCipher;
        pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM);
        // write AES key
        pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
        byte[] pkEncryptedKey = pkCipher.doFinal(key);
        String alg = pkCipher.getAlgorithm();
        Log.i(t, "AlgorithmUsed: " + alg);
        base64RsaEncryptedSymmetricKey = wrapper.encodeToString(pkEncryptedKey);

      } catch (NoSuchAlgorithmException e) {
        Log.e(t, "Unable to encrypt the symmetric key");
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      } catch (NoSuchPaddingException e) {
        Log.e(t, "Unable to encrypt the symmetric key");
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      } catch (InvalidKeyException e) {
        Log.e(t, "Unable to encrypt the symmetric key");
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      } catch (IllegalBlockSizeException e) {
        Log.e(t, "Unable to encrypt the symmetric key");
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      } catch (BadPaddingException e) {
        Log.e(t, "Unable to encrypt the symmetric key");
        e.printStackTrace();
        throw new IllegalArgumentException(e.getMessage());
      }

      // start building elementSignatureSource...
      appendElementSignatureSource(formId);
      if (formVersion != null) {
        appendElementSignatureSource(formVersion.toString());
      }
      appendElementSignatureSource(base64RsaEncryptedSymmetricKey);

      appendElementSignatureSource(instanceMetadata.instanceId);
    }
  private static boolean decryptSubmissionFiles(
      String base64EncryptedSymmetricKey,
      FormInstanceMetadata fim,
      List<String> mediaNames,
      String encryptedSubmissionFile,
      String base64EncryptedElementSignature,
      PrivateKey rsaPrivateKey,
      File instanceDir,
      File unencryptedDir)
      throws FileSystemException, CryptoException, ParsingException {

    EncryptionInformation ei =
        new EncryptionInformation(base64EncryptedSymmetricKey, fim.instanceId, rsaPrivateKey);

    byte[] elementDigest;
    try {
      // construct the base64-encoded RSA-encrypted symmetric key
      Cipher pkCipher;
      pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM);
      // extract digest
      pkCipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
      byte[] encryptedElementSignature = Base64.decodeBase64(base64EncryptedElementSignature);
      elementDigest = pkCipher.doFinal(encryptedElementSignature);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      throw new CryptoException(
          "Error decrypting base64EncryptedElementSignature Cause: " + e.toString());
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
      throw new CryptoException(
          "Error decrypting base64EncryptedElementSignature Cause: " + e.toString());
    } catch (InvalidKeyException e) {
      e.printStackTrace();
      throw new CryptoException(
          "Error decrypting base64EncryptedElementSignature Cause: " + e.toString());
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
      throw new CryptoException(
          "Error decrypting base64EncryptedElementSignature Cause: " + e.toString());
    } catch (BadPaddingException e) {
      e.printStackTrace();
      throw new CryptoException(
          "Error decrypting base64EncryptedElementSignature Cause: " + e.toString());
    }

    // NOTE: will decrypt only the files in the media list, plus the encryptedSubmissionFile

    File[] allFiles = instanceDir.listFiles();
    List<File> filesToProcess = new ArrayList<File>();
    for (File f : allFiles) {
      if (mediaNames.contains(f.getName())) {
        filesToProcess.add(f);
      } else if (encryptedSubmissionFile.equals(f.getName())) {
        filesToProcess.add(f);
      }
    }

    // should have all media files plus one submission.xml.enc file
    if (filesToProcess.size() != mediaNames.size() + 1) {
      // figure out what we're missing...
      int lostFileCount = 0;
      List<String> missing = new ArrayList<String>();
      for (String name : mediaNames) {
        if (name == null) {
          // this was lost due to an pre-ODK Aggregate 1.4.5 mark-as-complete action
          ++lostFileCount;
          continue;
        }
        File f = new File(instanceDir, name);
        if (!filesToProcess.contains(f)) {
          missing.add(name);
        }
      }
      StringBuilder b = new StringBuilder();
      for (String name : missing) {
        b.append(" ").append(name);
      }
      if (!filesToProcess.contains(new File(instanceDir, encryptedSubmissionFile))) {
        b.append(" ").append(encryptedSubmissionFile);
        throw new FileSystemException(
            "Error decrypting: " + instanceDir.getName() + " Missing files:" + b.toString());
      } else {
        // ignore the fact that we don't have the lost files
        if (filesToProcess.size() + lostFileCount != mediaNames.size() + 1) {
          throw new FileSystemException(
              "Error decrypting: " + instanceDir.getName() + " Missing files:" + b.toString());
        }
      }
    }

    // decrypt the media files IN ORDER.
    for (String mediaName : mediaNames) {
      String displayedName = (mediaName == null) ? "<missing .enc file>" : mediaName;
      File f = (mediaName == null) ? null : new File(instanceDir, mediaName);
      try {
        decryptFile(ei, f, unencryptedDir);
      } catch (InvalidKeyException e) {
        e.printStackTrace();
        throw new CryptoException("Error decrypting:" + displayedName + " Cause: " + e.toString());
      } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new CryptoException("Error decrypting:" + displayedName + " Cause: " + e.toString());
      } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
        throw new CryptoException("Error decrypting:" + displayedName + " Cause: " + e.toString());
      } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        throw new CryptoException("Error decrypting:" + displayedName + " Cause: " + e.toString());
      } catch (IOException e) {
        e.printStackTrace();
        throw new FileSystemException(
            "Error decrypting:" + displayedName + " Cause: " + e.toString());
      }
    }

    // decrypt the submission file
    File f = new File(instanceDir, encryptedSubmissionFile);
    try {
      decryptFile(ei, f, unencryptedDir);
    } catch (InvalidKeyException e) {
      e.printStackTrace();
      throw new CryptoException("Error decrypting:" + f.getName() + " Cause: " + e.toString());
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      throw new CryptoException("Error decrypting:" + f.getName() + " Cause: " + e.toString());
    } catch (InvalidAlgorithmParameterException e) {
      e.printStackTrace();
      throw new CryptoException("Error decrypting:" + f.getName() + " Cause: " + e.toString());
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
      throw new CryptoException("Error decrypting:" + f.getName() + " Cause: " + e.toString());
    } catch (IOException e) {
      e.printStackTrace();
      throw new FileSystemException("Error decrypting:" + f.getName() + " Cause: " + e.toString());
    }

    // get the FIM for the decrypted submission file
    File submissionFile =
        new File(
            unencryptedDir,
            encryptedSubmissionFile.substring(0, encryptedSubmissionFile.lastIndexOf(".enc")));

    FormInstanceMetadata submissionFim;
    try {
      Document subDoc = XmlManipulationUtils.parseXml(submissionFile);
      submissionFim = XmlManipulationUtils.getFormInstanceMetadata(subDoc.getRootElement());
    } catch (ParsingException e) {
      e.printStackTrace();
      throw new FileSystemException(
          "Error decrypting: " + submissionFile.getName() + " Cause: " + e.toString());
    } catch (FileSystemException e) {
      e.printStackTrace();
      throw new FileSystemException(
          "Error decrypting: " + submissionFile.getName() + " Cause: " + e.getMessage());
    }

    boolean same = submissionFim.xparam.formId.equals(fim.xparam.formId);

    if (!same) {
      throw new FileSystemException(
          "Error decrypting:"
              + unencryptedDir.getName()
              + " Cause: form instance metadata differs from that in manifest");
    }

    // Construct the element signature string
    StringBuilder b = new StringBuilder();
    appendElementSignatureSource(b, fim.xparam.formId);
    if (fim.xparam.modelVersion != null) {
      appendElementSignatureSource(b, Long.toString(fim.xparam.modelVersion));
    }
    appendElementSignatureSource(b, base64EncryptedSymmetricKey);

    appendElementSignatureSource(b, fim.instanceId);

    boolean missingFile = false;
    for (String encFilename : mediaNames) {
      if (encFilename == null) {
        missingFile = true;
        continue;
      }
      File decryptedFile =
          new File(unencryptedDir, encFilename.substring(0, encFilename.lastIndexOf(".enc")));
      if (decryptedFile.getName().endsWith(".missing")) {
        // this is a missing file -- we will not be able to
        // confirm the signature of the submission.
        missingFile = true;
        continue;
      }
      String md5 = FileSystemUtils.getMd5Hash(decryptedFile);
      appendElementSignatureSource(b, decryptedFile.getName() + "::" + md5);
    }

    String md5 = FileSystemUtils.getMd5Hash(submissionFile);
    appendElementSignatureSource(b, submissionFile.getName() + "::" + md5);

    // compute the digest of the element signature string
    byte[] messageDigest;
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(b.toString().getBytes("UTF-8"));
      messageDigest = md.digest();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      throw new CryptoException("Error computing xml signature Cause: " + e.toString());
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      throw new CryptoException("Error computing xml signature Cause: " + e.toString());
    }

    same = true;
    for (int i = 0; i < messageDigest.length; ++i) {
      if (messageDigest[i] != elementDigest[i]) {
        same = false;
        break;
      }
    }

    return same;
  }
Пример #20
0
  @Override
  public void create(JProgressBar progressBar) throws IOException {
    // Calculate piece_hashes
    MessageDigest digest = null;
    try {
      digest = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException nsa) {
      throw new InternalError(nsa.toString());
    }

    byte[] pieceHashes = metainfo.getPieceHashes();

    byte[] piece = new byte[subpieceSize * BitField.NUM_SUBPIECES_PER_PIECE];
    for (int i = 0; i < (nbSubpieces / BitField.NUM_SUBPIECES_PER_PIECE) + 1; i++) {
      if (progressBar != null && (i % 100 == 0)) {
        int percentComplete = i / ((nbSubpieces / BitField.NUM_SUBPIECES_PER_PIECE) + 1);
        progressBar.setValue(percentComplete);
      }
      int pieceLength = getUncheckedPiece(i, piece);
      if (pieceLength > 0) {
        digest.update(piece, 0, pieceLength);
        byte[] hash = digest.digest();
        System.arraycopy(
            hash,
            0,
            pieceHashes,
            VodConfig.NUM_HASHES_IN_TORRENT_FILE * i,
            VodConfig.NUM_HASHES_IN_TORRENT_FILE);
        for (int j = 0; j < metainfo.getPieceNbSubPieces(i); j++) {
          bitfield.set(i * BitField.NUM_SUBPIECES_PER_PIECE + j, true);
        }
      }
    }

    boolean[] initializedPieceHash = metainfo.getInitializedPieceHashes();
    byte[] chunkHash = metainfo.getChunksHashes();

    byte[] chunk = new byte[BitField.NUM_PIECES_PER_CHUNK * VodConfig.NUM_HASHES_IN_TORRENT_FILE];
    for (int i = 0;
        i
            < pieceHashes.length
                / BitField.NUM_PIECES_PER_CHUNK
                / VodConfig.NUM_HASHES_IN_TORRENT_FILE;
        i++) {
      for (int j = 0;
          j < BitField.NUM_PIECES_PER_CHUNK * VodConfig.NUM_HASHES_IN_TORRENT_FILE;
          j++) {
        chunk[j] =
            pieceHashes[
                i * BitField.NUM_PIECES_PER_CHUNK * VodConfig.NUM_HASHES_IN_TORRENT_FILE + j];
      }
      digest.update(chunk, 0, chunk.length);
      byte[] hash = digest.digest();
      System.arraycopy(
          hash,
          0,
          chunkHash,
          VodConfig.NUM_HASHES_IN_TORRENT_FILE * i,
          VodConfig.NUM_HASHES_IN_TORRENT_FILE);
      initializedPieceHash[i] = true;
    }
    // Reannounce to force recalculating the info_hash.
    metainfo = metainfo.reannounce();
  }