Пример #1
1
  public static void logTokens(Activity context) {

    // Add code to print out the key hash
    try {
      PackageInfo info =
          context
              .getPackageManager()
              .getPackageInfo(
                  context.getApplicationContext().getPackageName(), PackageManager.GET_SIGNATURES);
      for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(signature.toByteArray());
        Log.d("SHA-KeyHash:::", Base64.encodeToString(md.digest(), Base64.DEFAULT));

        md = MessageDigest.getInstance("MD5");
        md.update(signature.toByteArray());
        Log.d("MD5-KeyHash:::", Base64.encodeToString(md.digest(), Base64.DEFAULT));

        md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("SHA-Hex-From-KeyHash:::", bytesToHex(md.digest()));
      }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }
  }
Пример #2
0
 /**
  * Returns true if the given values match the commitment given.
  *
  * @param commitment
  * @param value
  * @param randomness
  * @return
  */
 public static boolean checkCommitment(
     MessageDigest H, BigInteger commitment, BigInteger value, BigInteger randomness) {
   H.update(value.toByteArray());
   H.update(randomness.toByteArray());
   BigInteger testSubject = new BigInteger(H.digest()).mod(Util.getModulus());
   return commitment.equals(testSubject);
 }
 private static void appendArray(MessageDigest digest, Object value) {
   digest.update("A".getBytes());
   for (int i = 0; i < Array.getLength(value); i++) {
     appendObject(digest, Array.get(value, i));
     digest.update(",".getBytes());
   }
 }
Пример #4
0
  /**
   * 对报文进行采用MD5进行hmac签名
   *
   * @param aValue - 字符�?
   * @param aKey - 密钥
   * @param encoding - 字符串编码方�?
   * @return - 签名结果,hex字符�?
   */
  public static String hmacSign(String aValue, String aKey, String encoding) {
    byte k_ipad[] = new byte[64];
    byte k_opad[] = new byte[64];
    byte keyb[];
    byte value[];
    try {
      keyb = aKey.getBytes(encoding);
      value = aValue.getBytes(encoding);
    } catch (UnsupportedEncodingException e) {
      keyb = aKey.getBytes();
      value = aValue.getBytes();
    }
    Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
    Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
    for (int i = 0; i < keyb.length; i++) {
      k_ipad[i] = (byte) (keyb[i] ^ 0x36);
      k_opad[i] = (byte) (keyb[i] ^ 0x5c);
    }

    MessageDigest md = null;
    try {
      md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    }
    md.update(k_ipad);
    md.update(value);
    byte dg[] = md.digest();
    md.reset();
    md.update(k_opad);
    md.update(dg, 0, 16);
    dg = md.digest();
    return ConvertUtils.toHex(dg);
  }
  /**
   * Computes the serial version UID value for the given class. The code is taken from {@link
   * ObjectStreamClass#computeDefaultSUID(Class)}.
   *
   * @param cls A class.
   * @return A serial version UID.
   * @throws IOException If failed.
   */
  static long computeSerialVersionUid(Class cls) throws IOException {
    if (Serializable.class.isAssignableFrom(cls) && !Enum.class.isAssignableFrom(cls)) {
      return ObjectStreamClass.lookup(cls).getSerialVersionUID();
    }

    MessageDigest md;

    try {
      md = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
      throw new IOException("Failed to get digest for SHA.", e);
    }

    md.update(cls.getName().getBytes(UTF_8));

    for (Field f : getFieldsForSerialization(cls)) {
      md.update(f.getName().getBytes(UTF_8));
      md.update(f.getType().getName().getBytes(UTF_8));
    }

    byte[] hashBytes = md.digest();

    long hash = 0;

    // Composes a single-long hash from the byte[] hash.
    for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--)
      hash = (hash << 8) | (hashBytes[i] & 0xFF);

    return hash;
  }
Пример #6
0
  /**
   * @param key
   * @param update_key
   * @return
   * @throws CryptoException
   */
  public byte[] update(byte[] key, byte[] update_key) throws CryptoException {
    byte[] shasig = new byte[20];
    byte[] update = new byte[this.keylength]; // changed from 8 - rdesktop
    // 1.2.0
    byte[] thekey = new byte[key.length];

    synchronized (digestLock) {
      sha1.reset();
      sha1.update(update_key, 0, keylength);
      sha1.update(pad_54, 0, 40);
      sha1.update(key, 0, keylength); // changed from 8 - rdesktop
      // 1.2.0
      shasig = sha1.digest();
      sha1.reset();

      md5.reset();
      md5.update(update_key, 0, keylength); // changed from 8 - rdesktop
      // 1.2.0
      md5.update(pad_92, 0, 48);
      md5.update(shasig, 0, 20);
      thekey = md5.digest();
      md5.reset();

      System.arraycopy(thekey, 0, update, 0, this.keylength);
      rc4_update.engineInitDecrypt(update);
      // added
      thekey = rc4_update.crypt(thekey, 0, this.keylength);

      if (this.keylength == 8) {
        this.make40bit(thekey);
      }
    }

    return thekey;
  }
Пример #7
0
  /**
   * Generate the mask.
   *
   * @param seed source of input bytes for initial digest state
   * @param length length of mask to generate
   * @return a byte array containing a MGF1 generated mask
   */
  public byte[] generateMask(byte[] seed, int length) {
    byte[] mask = new byte[length];
    byte[] C = new byte[4];
    int counter = 0;
    int hLen = digest.getDigestLength();

    digest.reset();

    while (counter < (length / hLen)) {
      ItoOSP(counter, C);

      digest.update(seed);
      digest.update(C);

      System.arraycopy(digest.digest(), 0, mask, counter * hLen, hLen);

      counter++;
    }

    if ((counter * hLen) < length) {
      ItoOSP(counter, C);

      digest.update(seed);
      digest.update(C);

      System.arraycopy(digest.digest(), 0, mask, counter * hLen, mask.length - (counter * hLen));
    }

    return mask;
  }
  /**
   * Calculates the hash of password (and salt bytes, if supplied) and returns a base64 encoded
   * concatenation of the hash and salt, prefixed with {SHA} (or {SSHA} if salt was used).
   *
   * @param rawPass the password to be encoded.
   * @param salt the salt. Must be a byte array or null.
   * @return the encoded password in the specified format
   */
  public String encodePassword(String rawPass, Object salt) {
    MessageDigest sha;

    try {
      sha = MessageDigest.getInstance("SHA");
      sha.update(rawPass.getBytes("UTF-8"));
    } catch (java.security.NoSuchAlgorithmException e) {
      throw new IllegalStateException("No SHA implementation available!");
    } catch (UnsupportedEncodingException ue) {
      throw new IllegalStateException("UTF-8 not supported!");
    }

    if (salt != null) {
      Assert.isInstanceOf(byte[].class, salt, "Salt value must be a byte array");
      sha.update((byte[]) salt);
    }

    byte[] hash = combineHashAndSalt(sha.digest(), (byte[]) salt);

    String prefix;

    if (salt == null) {
      prefix = forceLowerCasePrefix ? SHA_PREFIX_LC : SHA_PREFIX;
    } else {
      prefix = forceLowerCasePrefix ? SSHA_PREFIX_LC : SSHA_PREFIX;
    }

    return prefix + new String(Base64.encode(hash));
  }
  private byte[] createRFC2617RequestDigest(
      final byte[] ha1, final byte[] ha2, final DigestContext context) {
    final MessageDigest digest = context.getDigest();
    final Map<DigestAuthorizationToken, String> parsedHeader = context.getParsedHeader();

    byte[] nonce =
        parsedHeader.get(DigestAuthorizationToken.NONCE).getBytes(StandardCharsets.UTF_8);
    byte[] nonceCount =
        parsedHeader.get(DigestAuthorizationToken.NONCE_COUNT).getBytes(StandardCharsets.UTF_8);
    byte[] cnonce =
        parsedHeader.get(DigestAuthorizationToken.CNONCE).getBytes(StandardCharsets.UTF_8);
    byte[] qop =
        parsedHeader.get(DigestAuthorizationToken.MESSAGE_QOP).getBytes(StandardCharsets.UTF_8);

    try {
      digest.update(ha1);
      digest.update(COLON);
      digest.update(nonce);
      digest.update(COLON);
      digest.update(nonceCount);
      digest.update(COLON);
      digest.update(cnonce);
      digest.update(COLON);
      digest.update(qop);
      digest.update(COLON);
      digest.update(ha2);

      return HexConverter.convertToHexBytes(digest.digest());
    } finally {
      digest.reset();
    }
  }
Пример #10
0
  /**
   * Completes the Mac computation and resets the Mac for further use, maintaining the secret key
   * that the Mac was initialized with.
   *
   * @return the Mac result.
   */
  byte[] doFinal() {
    if (first == true) {
      // compute digest for 1st pass; start with inner pad
      md.update(secret);
      md.update(pad1);
    } else {
      first = true;
    }

    try {
      // finish the inner digest
      byte[] tmp = md.digest();

      // compute digest for 2nd pass; start with outer pad
      md.update(secret);
      md.update(pad2);
      // add result of 1st hash
      md.update(tmp);

      md.digest(tmp, 0, tmp.length);
      return tmp;
    } catch (DigestException e) {
      // should never occur
      throw new ProviderException(e);
    }
  }
  public String calculateHash(String graph) throws SQLException, NoSuchAlgorithmException {
    // TODO: sanitize graph

    MessageDigest digest = MessageDigest.getInstance("SHA-512"); // takes 50 sec on Fly data
    //		MessageDigest digest = MessageDigest.getInstance("MD5"); // takes 46 sec on Fly data

    // cb66cc5f1feb5169542af48342936ad2962a8ae14840f1e029028636004f779346c19ecd0917ea2f53c6ec94f4ab10c5bffc272888ae33b73797bdee9cb7193a

    Statement st = con.createStatement();
    try {

      ResultSet rs =
          executeQuery(st, "SPARQL SELECT ?s ?p ?o FROM <" + graph + "> WHERE { ?s ?p ?o . }");
      while (rs.next()) {
        digest.update(rs.getString(1).getBytes());
        digest.update(rs.getString(2).getBytes());
        digest.update(rs.getString(3).getBytes());
      }

    } catch (VirtuosoException ex) {
      rethrowWithTips(ex);
    }
    String hexString = new String(Hex.encodeHex(digest.digest()));
    return hexString;
  }
 /**
  * Flush and invoke appropriate optype
  *
  * @param optype the optype
  * @param index the index
  * @param type the type
  * @param id the id
  * @throws IOException
  */
 public void flush(String optype, String index, String type, String id) throws IOException {
   if (!map.isEmpty()) {
     build(map);
     if (listener != null) {
       if ("create".equals(optype)) {
         listener.create(index, type, id, version, builder);
       } else if ("index".equals(optype)) {
         listener.index(index, type, id, version, builder);
       } else if ("delete".equals(optype)) {
         listener.delete(index, type, id);
       }
     }
     if (index != null) {
       digest.update(index.getBytes("UTF-8"));
     }
     if (type != null) {
       digest.update(type.getBytes("UTF-8"));
     }
     if (id != null) {
       digest.update(id.getBytes("UTF-8"));
     }
     builder.close();
     builder = jsonBuilder();
     map = new HashMap();
   }
 }
  boolean isManifestUpdated() {
    if (!mCacheFile.exists()) {
      Log.i("ManifestCheckerService", "updated: cache file does not exist");
      return true;
    }

    try {
      MessageDigest dataDigester = MessageDigest.getInstance("MD5");
      dataDigester.update(mFetcher.getData(), 0, mFetcher.getDataLen());
      byte[] dataDigest = dataDigester.digest();

      MessageDigest fileDigester = MessageDigest.getInstance("MD5");
      FileInputStream is = new FileInputStream(mCacheFile);
      byte[] buf = new byte[4096];
      int len;
      while ((len = is.read(buf)) > 0) {
        fileDigester.update(buf, 0, len);
      }
      is.close();
      byte[] fileDigest = fileDigester.digest();

      if (Arrays.equals(dataDigest, fileDigest)) {
        return false;
      }
      Log.i("ManifestCheckerService", "updated: digests differ");
    } catch (Exception e) {
      Log.e("ManifestFetcher", "caught exception: " + e.getMessage());
      e.printStackTrace();
    }

    return true;
  }
Пример #14
0
  private boolean verify(
      Attributes attributes,
      String entry,
      byte[] data,
      int start,
      int end,
      boolean ignoreSecondEndline,
      boolean ignorable) {
    for (int i = 0; i < DIGEST_ALGORITHMS.length; i++) {
      String algorithm = DIGEST_ALGORITHMS[i];
      String hash = attributes.getValue(algorithm + entry);
      if (hash == null) {
        continue;
      }

      MessageDigest md;
      try {
        md = MessageDigest.getInstance(algorithm);
      } catch (NoSuchAlgorithmException e) {
        continue;
      }
      if (ignoreSecondEndline && data[end - 1] == '\n' && data[end - 2] == '\n') {
        md.update(data, start, end - 1 - start);
      } else {
        md.update(data, start, end - start);
      }
      byte[] b = md.digest();
      byte[] hashBytes = hash.getBytes(StandardCharsets.ISO_8859_1);
      return MessageDigest.isEqual(b, Base64.decode(hashBytes));
    }
    return ignorable;
  }
Пример #15
0
  private String hash(String clearPassword) {
    if (salt == 0) return null;

    MessageDigest md = null;
    try {
      md = MessageDigest.getInstance("SHA1");
    } catch (NoSuchAlgorithmException e) {
      throw new AssertionError("Can't find the SHA1 algorithm in the java.security package");
    }

    String saltString = String.valueOf(salt);

    md.update(saltString.getBytes());
    md.update(clearPassword.getBytes());
    byte[] digestBytes = md.digest();

    // Format the digest as a String
    StringBuffer digestSB = new StringBuffer();
    for (int i = 0; i < digestBytes.length; i++) {
      int lowNibble = digestBytes[i] & 0x0f;
      int highNibble = (digestBytes[i] >> 4) & 0x0f;
      digestSB.append(Integer.toHexString(highNibble));
      digestSB.append(Integer.toHexString(lowNibble));
    }
    String digestStr = digestSB.toString();

    return digestStr;
  }
Пример #16
0
 /**
  * 验证口令是否合法
  *
  * @param password
  * @param passwordInDb
  * @return
  * @throws NoSuchAlgorithmException
  * @throws UnsupportedEncodingException
  */
 public static boolean validPassword(String password, String passwordInDb)
     throws NoSuchAlgorithmException, UnsupportedEncodingException {
   // 将16进制字符串格式口令转换成字节数组
   byte[] pwdInDb = hexStringToByte(passwordInDb);
   // 声明盐变量
   byte[] salt = new byte[SALT_LENGTH];
   // 将盐从数据库中保存的口令字节数组中提取出来
   System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH);
   // 创建消息摘要对象
   MessageDigest md = MessageDigest.getInstance("MD5");
   // 将盐数据传入消息摘要对象
   md.update(salt);
   // 将口令的数据传给消息摘要对象
   md.update(password.getBytes("UTF-8"));
   // 生成输入口令的消息摘要
   byte[] digest = md.digest();
   // 声明一个保存数据库中口令消息摘要的变量
   byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH];
   // 取得数据库中口令的消息摘要
   System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length);
   // 比较根据输入口令生成的消息摘要和数据库中消息摘要是否相同
   if (Arrays.equals(digest, digestInDb)) {
     // 口令正确返回口令匹配消息
     return true;
   } else {
     // 口令不正确返回口令不匹配消息
     return false;
   }
 }
Пример #17
0
  /**
   * create from an issuer certificate and the serial number of the certificate it signed.
   *
   * @exception OCSPException if any problems occur creating the id fields.
   */
  public CertificateID(
      String hashAlgorithm, X509Certificate issuerCert, BigInteger number, String provider)
      throws OCSPException {
    try {
      MessageDigest digest = MessageDigest.getInstance(hashAlgorithm, provider);
      AlgorithmIdentifier hashAlg =
          new AlgorithmIdentifier(new DERObjectIdentifier(hashAlgorithm), new DERNull());

      X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(issuerCert);

      digest.update(issuerName.getEncoded());

      ASN1OctetString issuerNameHash = new DEROctetString(digest.digest());
      PublicKey issuerKey = issuerCert.getPublicKey();

      ASN1InputStream aIn = new ASN1InputStream(issuerKey.getEncoded());
      SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());

      digest.update(info.getPublicKeyData().getBytes());

      ASN1OctetString issuerKeyHash = new DEROctetString(digest.digest());

      DERInteger serialNumber = new DERInteger(number);

      this.id = new CertID(hashAlg, issuerNameHash, issuerKeyHash, serialNumber);
    } catch (Exception e) {
      throw new OCSPException("problem creating ID: " + e, e);
    }
  }
Пример #18
0
  /**
   * 获得加密后的16进制形式口令
   *
   * @param password
   * @return
   * @throws NoSuchAlgorithmException
   * @throws UnsupportedEncodingException
   */
  public static String getEncryptedPwd(String password)
      throws NoSuchAlgorithmException, UnsupportedEncodingException {
    // 声明加密后的口令数组变量
    byte[] pwd = null;
    // 随机数生成器
    SecureRandom random = new SecureRandom();
    // 声明盐数组变量
    byte[] salt = new byte[SALT_LENGTH];
    // 将随机数放入盐变量中
    random.nextBytes(salt);

    // 声明消息摘要对象
    MessageDigest md = null;
    // 创建消息摘要
    md = MessageDigest.getInstance("MD5");
    // 将盐数据传入消息摘要对象
    md.update(salt);
    // 将口令的数据传给消息摘要对象
    md.update(password.getBytes("UTF-8"));
    // 获得消息摘要的字节数组
    byte[] digest = md.digest();

    // 因为要在口令的字节数组中存放盐,所以加上盐的字节长度
    pwd = new byte[digest.length + SALT_LENGTH];
    // 将盐的字节拷贝到生成的加密口令字节数组的前12个字节,以便在验证口令时取出盐
    System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH);
    // 将消息摘要拷贝到加密口令字节数组从第13个字节开始的字节
    System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length);
    // 将字节数组格式加密后的口令转化为16进制字符串格式的口令
    return byteToHexString(pwd);
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in first if */
  private void goodG2B2() throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_t) {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Logger log_bad = Logger.getLogger("local-logger");

      data = ""; /* init data */

      /* read user input from console with readLine*/
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        instrread = new InputStreamReader(System.in);
        buffread = new BufferedReader(instrread);
        data = buffread.readLine();
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (instrread != null) {
              instrread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing instrread");
          }
        }
      }
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_t) {
      MessageDigest hash = MessageDigest.getInstance("SHA-512");
      hash.update(data.getBytes()); /* FLAW: SHA512 with a predictable salt */
      byte[] hashv = hash.digest("hash me".getBytes());
      IO.writeLine(IO.toHex(hashv));
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      SecureRandom r = new SecureRandom();

      MessageDigest hash = MessageDigest.getInstance("SHA-512");
      hash.update(r.getSeed(32)); /* FIX: Use a sufficiently random salt */
      byte[] hashv = hash.digest("hash me".getBytes());

      IO.writeLine(IO.toHex(hashv));
    }
  }
  @Override
  public void send(Quad quad) {
    try {
      byte[] s = tdbloader3.serialize(quad.getSubject()).getBytes("UTF-8");
      byte[] p = tdbloader3.serialize(quad.getPredicate()).getBytes("UTF-8");
      byte[] o = tdbloader3.serialize(quad.getObject()).getBytes("UTF-8");
      byte[] g = null;
      // Union graph?!
      if (!quad.isTriple() && !quad.isDefaultGraph())
        g = tdbloader3.serialize(quad.getGraph()).getBytes("UTF-8");

      digest.reset();
      digest.update(s); // TODO: should we do something better here?
      digest.update(p);
      digest.update(o);
      if (g != null) digest.update(g.toString().getBytes("UTF-8"));

      String md5 = new String(Hex.encodeHex(digest.digest()));
      sdb01.add(new Pair<byte[], byte[]>(s, (md5 + "|s").getBytes("UTF-8")));
      sdb01.add(new Pair<byte[], byte[]>(p, (md5 + "|p").getBytes("UTF-8")));
      sdb01.add(new Pair<byte[], byte[]>(o, (md5 + "|o").getBytes("UTF-8")));
      if (g != null) sdb01.add(new Pair<byte[], byte[]>(g, (md5 + "|g").getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
      throw new AtlasException(e);
    }

    monitor.tick();
  }
Пример #21
0
  public static String GenerateHash(String url, Request request, boolean getRequest) {
    int start = HASH_SIZE * request.getAccessIndex();
    int end = start + HASH_SIZE;
    DaapHost host = request.getHost();
    calculateStaticHash(host);

    // System.out.println("Creating hash, reqid is " + reqid);

    if (host.getDaapVersion() >= DaapHost.ITUNES_45) {

      // System.out.println("Generating 4.5 Hash");

      //			nmd = new MD5();
      //			nmd.Update(url.getBytes());
      //			nmd.Update(appleCopyright.getBytes());
      //			nmd.Update(calcHash.substring(start, end).getBytes());
      //
      //			if (getRequest) {
      //				nmd.Update((new Integer(host.getThisRequestNumber())).toString().getBytes());
      //				// System.out.println("Adding this compontent");
      //
      //			}
      //			return DigestToString(nmd.Final());
      return "";

    } else {

      md.update(url.getBytes());
      md.update(appleCopyright.getBytes());
      md.update(calcHash.substring(start, end).getBytes());
      return DigestToString(md.digest());
    }
  }
Пример #22
0
  static void parseXml(Element p_element, MessageDigest p_md, ArrayList<String> p_ignoreList) {
    p_md.update(p_element.getName().getBytes());

    String content = p_element.getText();

    if (content != null) {
      p_md.update(content.getBytes());
    }

    for (Attribute attribute : p_element.getAttributes()) {
      String name = attribute.getName();

      if (p_ignoreList.contains(name)) {
        continue;
      }

      String value = attribute.getValue();

      if (value != null) {
        p_md.update(value.getBytes());
      }
    }

    for (Element child : p_element.getChildren()) {
      parseXml(child, p_md, p_ignoreList);
    }
  }
Пример #23
0
  public byte[] hash48(byte[] in, byte[] salt1, byte[] salt2, int salt) throws CryptoException {
    byte[] shasig = new byte[20];
    byte[] pad = new byte[4];
    byte[] out = new byte[48];
    int i = 0;

    synchronized (digestLock) {
      sha1.reset();
      md5.reset();
      for (i = 0; i < 3; i++) {
        for (int j = 0; j <= i; j++) {
          pad[j] = (byte) (salt + i);
        }
        sha1.update(pad, 0, i + 1);
        sha1.update(in, 0, 48);
        sha1.update(salt1, 0, 32);
        sha1.update(salt2, 0, 32);
        shasig = sha1.digest();
        sha1.reset();

        md5.update(in, 0, 48);
        md5.update(shasig, 0, 20);
        System.arraycopy(md5.digest(), 0, out, i * 16, 16);
      }
    }

    return out;
  }
Пример #24
0
  /**
   * Calculates the NTLM2 Session Response for the given challenge, using the specified password and
   * client challenge.
   *
   * @param password The user's password.
   * @param challenge The Type 2 challenge from the server.
   * @param clientChallenge The random 8-byte client challenge.
   * @return The NTLM2 Session Response. This is placed in the NTLM response field of the Type 3
   *     message; the LM response field contains the client challenge, null-padded to 24 bytes.
   */
  static byte[] getNTLM2SessionResponse(String password, byte[] challenge, byte[] clientChallenge)
      throws NTLMEngineException {
    try {
      byte[] ntlmHash = ntlmHash(password);

      // Look up MD5 algorithm (was necessary on jdk 1.4.2)
      // This used to be needed, but java 1.5.0_07 includes the MD5
      // algorithm (finally)
      // Class x = Class.forName("gnu.crypto.hash.MD5");
      // Method updateMethod = x.getMethod("update",new
      // Class[]{byte[].class});
      // Method digestMethod = x.getMethod("digest",new Class[0]);
      // Object mdInstance = x.newInstance();
      // updateMethod.invoke(mdInstance,new Object[]{challenge});
      // updateMethod.invoke(mdInstance,new Object[]{clientChallenge});
      // byte[] digest = (byte[])digestMethod.invoke(mdInstance,new
      // Object[0]);

      MessageDigest md5 = MessageDigest.getInstance("MD5");
      md5.update(challenge);
      md5.update(clientChallenge);
      byte[] digest = md5.digest();

      byte[] sessionHash = new byte[8];
      System.arraycopy(digest, 0, sessionHash, 0, 8);
      return lmResponse(ntlmHash, sessionHash);
    } catch (Exception e) {
      if (e instanceof NTLMEngineException) throw (NTLMEngineException) e;
      throw new NTLMEngineException(e.getMessage(), e);
    }
  }
Пример #25
0
  protected int engineDigest(byte[] buf, int offset, int len) throws DigestException {
    if (len < HASHSIZE) throw new DigestException();

    // hash any remaining fragments
    blockUpdate();

    // composite neighboring nodes together up to top value
    while (nodes.size() > 1) {
      List newNodes = new ArrayList();
      Iterator iter = nodes.iterator();
      while (iter.hasNext()) {
        byte[] left = (byte[]) iter.next();
        if (iter.hasNext()) {
          byte[] right = (byte[]) iter.next();
          tiger.reset();
          tiger.update((byte) 1); // node prefix
          tiger.update(left, 0, left.length);
          tiger.update(right, 0, right.length);
          newNodes.add(tiger.digest());
        } else {
          newNodes.add(left);
        }
      }
      nodes = newNodes;
    }
    System.arraycopy(nodes.get(0), 0, buf, offset, HASHSIZE);
    engineReset();
    return HASHSIZE;
  }
Пример #26
0
 /**
  * 产生MD5加密串
  *
  * @author huyong
  * @param plainText
  * @param charset
  * @return
  */
 private static String to32BitString(String plainText, String charset) {
   try {
     MessageDigest md = MessageDigest.getInstance("MD5");
     md.reset();
     if (charset != null) {
       md.update(plainText.getBytes(charset));
     } else {
       md.update(plainText.getBytes());
     }
     byte[] byteArray = md.digest();
     StringBuffer md5Buf = new StringBuffer();
     for (int i = 0; i < byteArray.length; i++) {
       if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
         md5Buf.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
       } else {
         md5Buf.append(Integer.toHexString(0xFF & byteArray[i]));
       }
     }
     return md5Buf.toString();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return null;
 }
Пример #27
0
 private static byte[][] evpBytesTokey(
     int key_len, int iv_len, MessageDigest md, byte[] salt, byte[] data, int count) {
   byte[][] both = new byte[2][];
   byte[] key = new byte[key_len];
   int key_ix = 0;
   byte[] iv = new byte[iv_len];
   int iv_ix = 0;
   both[0] = key;
   both[1] = iv;
   byte[] md_buf = null;
   int nkey = key_len;
   int niv = iv_len;
   int i = 0;
   if (data == null) {
     return both;
   }
   int addmd = 0;
   for (; ; ) {
     md.reset();
     if (addmd++ > 0) {
       md.update(md_buf);
     }
     md.update(data);
     if (null != salt) {
       md.update(salt, 0, 8);
     }
     md_buf = md.digest();
     for (i = 1; i < count; i++) {
       md.reset();
       md.update(md_buf);
       md_buf = md.digest();
     }
     i = 0;
     if (nkey > 0) {
       for (; ; ) {
         if (nkey == 0) break;
         if (i == md_buf.length) break;
         key[key_ix++] = md_buf[i];
         nkey--;
         i++;
       }
     }
     if (niv > 0 && i != md_buf.length) {
       for (; ; ) {
         if (niv == 0) break;
         if (i == md_buf.length) break;
         iv[iv_ix++] = md_buf[i];
         niv--;
         i++;
       }
     }
     if (nkey == 0 && niv == 0) {
       break;
     }
   }
   for (i = 0; i < md_buf.length; i++) {
     md_buf[i] = 0;
   }
   return both;
 }
  private static String sha1Hash(Object[] input) {
    try {
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      md.reset();

      for (Object o : input) {
        if (o instanceof String) {
          md.update(((String) o).getBytes("ISO_8859_1"));
        } else if (o instanceof byte[]) {
          md.update((byte[]) o);
        } else {
          return null;
        }
      }

      BigInteger bigInt = new BigInteger(md.digest());

      if (bigInt.compareTo(BigInteger.ZERO) < 0) {
        bigInt = bigInt.negate();
        return "-" + bigInt.toString(16);
      } else {
        return bigInt.toString(16);
      }
    } catch (Exception ioe) {
      return null;
    }
  }
 private static void appendList(MessageDigest digest, List<?> value) {
   digest.update("L".getBytes());
   for (Object object : value) {
     appendObject(digest, object);
     digest.update(",".getBytes());
   }
 }
Пример #30
0
  /**
   * Decodes the passed encrypted password and returns the clear-text form.
   *
   * @param encryptedPass encrypted password
   * @param sharedSecret shared secret
   * @return decrypted password
   */
  private String decodePapPassword(byte[] encryptedPass, byte[] sharedSecret)
      throws RadiusException {
    if (encryptedPass == null || encryptedPass.length < 16) {
      // PAP passwords require at least 16 bytes
      logger.warn(
          "invalid Radius packet: User-Password attribute with malformed PAP password, length = "
              + (encryptedPass == null ? 0 : encryptedPass.length)
              + ", but length must be greater than 15");
      throw new RadiusException("malformed User-Password attribute");
    }

    MessageDigest md5 = getMd5Digest();
    byte[] lastBlock = new byte[16];

    for (int i = 0; i < encryptedPass.length; i += 16) {
      md5.reset();
      md5.update(sharedSecret);
      md5.update(i == 0 ? getAuthenticator() : lastBlock);
      byte bn[] = md5.digest();

      System.arraycopy(encryptedPass, i, lastBlock, 0, 16);

      // perform the XOR as specified by RFC 2865.
      for (int j = 0; j < 16; j++) encryptedPass[i + j] = (byte) (bn[j] ^ encryptedPass[i + j]);
    }

    // remove trailing zeros
    int len = encryptedPass.length;
    while (len > 0 && encryptedPass[len - 1] == 0) len--;
    byte[] passtrunc = new byte[len];
    System.arraycopy(encryptedPass, 0, passtrunc, 0, len);

    // convert to string
    return RadiusUtil.getStringFromUtf8(passtrunc);
  }