Ejemplo n.º 1
0
  private boolean verifyPassword(
      String inputPassword, String storedPasswordHash, String storedSalt) {
    MessageDigest digest;
    try {
      digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      logger.error("MD5 is an invalid algorithm!", e);
      return false;
    }

    byte[] inputPasswordHash = digest.digest(inputPassword.getBytes());
    digest.reset();

    byte[] storedSaltHash = digest.digest(storedSalt.getBytes());
    digest.reset();

    byte[] finalHash =
        digest.digest(
            new StringBuilder()
                .append(toHexString(storedSaltHash))
                .append(toHexString(inputPasswordHash))
                .toString()
                .getBytes());

    return toHexString(finalHash).equalsIgnoreCase(storedPasswordHash);
  }
Ejemplo n.º 2
0
  /**
   * Generate MD5 signature
   *
   * @param session_key Key with which to sign data
   * @param length Length of signature
   * @param keylen Length of key
   * @param data Data to sign
   * @param datalength Length of data to sign
   * @return Signature for data
   * @throws CryptoException
   */
  public byte[] sign(byte[] session_key, int length, int keylen, byte[] data, int datalength)
      throws CryptoException {
    byte[] shasig = new byte[20];
    byte[] md5sig = new byte[16];
    byte[] lenhdr = new byte[4];
    byte[] signature = new byte[length];

    this.setLittleEndian32(lenhdr, datalength);

    synchronized (digestLock) {
      sha1.reset();
      sha1.update(session_key, 0, keylen);
      sha1.update(pad_54, 0, 40);
      sha1.update(lenhdr, 0, 4);
      sha1.update(data, 0, datalength);
      shasig = sha1.digest();
      sha1.reset();

      md5.reset();
      md5.update(session_key, 0, keylen /* length */);
      md5.update(pad_92, 0, 48);
      md5.update(shasig, 0, 20);
      md5sig = md5.digest();
      md5.reset();

      System.arraycopy(md5sig, 0, signature, 0, length);
    }
    return signature;
  }
Ejemplo n.º 3
0
 /**
  * encrypt
  *
  * @param content
  * @return
  */
 public static String encryptByMD5(String content) {
   try {
     MessageDigest algorithm = null;
     algorithm = MessageDigest.getInstance("MD5");
     algorithm.reset();
     if (content != null) {
       algorithm.reset();
       algorithm.update(content.getBytes());
       byte digest[] = algorithm.digest();
       StringBuffer hexString = new StringBuffer();
       int digestLength = digest.length;
       for (int i = 0; i < digestLength; i++) {
         if (i > 0) {
           hexString.append("-");
         }
         hexString.append(hexDigit(digest[i]));
       }
       return hexString.toString();
     } else {
       return "";
     }
   } catch (NoSuchAlgorithmException ex) {
     return content;
   }
 }
Ejemplo n.º 4
0
 private void reset(
     FSRevisionNode revNode,
     CountingOutputStream targetFileOS,
     File targetFile,
     InputStream source,
     long deltaStart,
     long repSize,
     long repOffset,
     FSTransactionRoot txnRoot,
     FSWriteLock txnLock) {
   myTxnRoot = txnRoot;
   myTargetFileOS = targetFileOS;
   myTargetFile = targetFile;
   mySourceStream = source;
   myDeltaStart = deltaStart;
   myRepSize = repSize;
   myRepOffset = repOffset;
   isHeaderWritten = false;
   myRevNode = revNode;
   mySourceOffset = 0;
   myIsClosed = false;
   myMD5Digest.reset();
   mySHA1Digest.reset();
   myTextBuffer.reset();
   myTxnLock = txnLock;
 }
Ejemplo n.º 5
0
    @Override
    public void onEvent(byte[] data, long seq, boolean endOfBatch) throws Exception {
      crc32.update(data);
      long crc = crc32.getValue();

      byte[] md5 = md5Digest.digest(data);
      byte[] sha1 = sha1Digest.digest(data);

      Data d = new Data(String.valueOf(crc), toHex(md5), toHex(sha1));
      int size = contexts.size();

      for (int i = 0; i < size; i++) {
        AsyncContext context = contexts.poll();
        if (null != context) {
          context.getRequest().setAttribute("data", d);
          try {
            context.dispatch();
          } catch (Exception e) {
          }
        } else {
          break;
        }
      }

      crc32.reset();
      md5Digest.reset();
      sha1Digest.reset();
    }
Ejemplo n.º 6
0
  public void calculate_M1() {
    BigInteger N_Hash;
    BigInteger g_Hash;
    BigInteger I_Hash;

    try {
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      // Calculate H(N)
      N_Hash = new BigInteger(md.digest(N.toString().getBytes()));
      md.reset();

      // Calculate H(g)
      g_Hash = new BigInteger(md.digest(g.toString().getBytes()));
      md.reset();

      // Calculate H(I)
      I_Hash = new BigInteger(md.digest(I.toString().getBytes()));
      md.reset();

      // Calculate M1
      M1 =
          new BigInteger(
              md.digest(
                  (N_Hash.xor(g_Hash).toString()
                          + I_Hash.toString()
                          + s.toString()
                          + A.toString()
                          + B.toString()
                          + K.toString())
                      .getBytes()));
      System.out.println("Client M1: " + M1.toString());
    } catch (Exception e) {
    }
  }
Ejemplo n.º 7
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;
 }
Ejemplo n.º 8
0
  /**
   * Encrypts given password using salt. Uses algorithm that makes password non-decryptable, because
   * no-one should ever be able to see passwords. Salt is used to make passwords secure against
   * precomputed hashes (<a href="http://en.wikipedia.org/wiki/Rainbow_table" target="_blank">see
   * here</a>). The reason for all this is that mostly all algorithms used for encryption are open
   * source.
   *
   * @param pword The password to be encrypted.
   * @param salt The salt to use in encryption. It should be a randomly generated number, and
   *     preferrably of fixed length.
   * @return Encrypted password.
   */
  private static byte[] getHash(String pword, byte[] salt) {
    byte[] input = null;
    try {

      /*
       * Get digester and update it with given salt. Using SHA-1
       * algorithm. See:
       * http://docs.oracle.com/javase/7/docs/technotes/guides
       * /security/StandardNames.html#MessageDigest for supported
       * algorithms.
       */
      MessageDigest digest = MessageDigest.getInstance("SHA-1");
      digest.reset();
      digest.update(salt);

      /*
       * Digest password according to ITERATION_COUNT. See:
       * http://docs.oracle
       * .com/javase/7/docs/api/java/nio/charset/Charset.html for
       * supported charsets.
       */
      input = digest.digest(pword.getBytes("UTF-8"));
      for (int i = 0; i < UserHandler.ITERATION_COUNT; i++) {
        digest.reset();
        input = digest.digest(input);
      }
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
      /*
       * These should never happen, as chosen algorithm and encoding are
       * both legit. NOTE: Be careful if you change them.
       */
    }
    return input;
  }
Ejemplo n.º 9
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;
  }
Ejemplo n.º 10
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;
  }
  /*
   * Initial IV client to server: HASH (K || H || "A" || session_id) Initial
   * IV server to client: HASH (K || H || "B" || session_id) Encryption key
   * client to server: HASH (K || H || "C" || session_id) Encryption key
   * server to client: HASH (K || H || "D" || session_id) Integrity key client
   * to server: HASH (K || H || "E" || session_id) Integrity key server to
   * client: HASH (K || H || "F" || session_id)
   */
  public void init(
      String encryptionAlgorithm,
      String cipherAlgorithm,
      int keyLength,
      String macAlgorithm,
      byte[] K,
      byte[] H,
      byte[] sessionId)
      throws GeneralSecurityException {
    MessageDigest sha = MessageDigest.getInstance("SHA-1");

    sha.reset();
    sha.update(
        new SshPacketBuilder().writeMpInt(K).append(H).writeByte('A').append(sessionId).finish());
    byte[] iv = sha.digest();

    sha.reset();
    sha.update(
        new SshPacketBuilder().writeMpInt(K).append(H).writeByte('C').append(sessionId).finish());
    byte[] cipherKey = sha.digest();

    try {
      cipher = Cipher.getInstance(encryptionAlgorithm + "/" + cipherAlgorithm + "/NoPadding");

      iv = CipherUtils.expandKey(K, H, iv, sha, cipher.getBlockSize());
      cipherKey = CipherUtils.expandKey(K, H, cipherKey, sha, keyLength);

      iv = CipherUtils.shrinkKey(iv, cipher.getBlockSize());
      cipherKey = CipherUtils.shrinkKey(cipherKey, keyLength);

      cipher.init(
          Cipher.ENCRYPT_MODE,
          new SecretKeySpec(cipherKey, encryptionAlgorithm),
          new IvParameterSpec(iv));

      sha.reset();
      sha.update(
          new SshPacketBuilder().writeMpInt(K).append(H).writeByte('E').append(sessionId).finish());
      byte[] macKey = sha.digest();

      mac = Mac.getInstance(macAlgorithm);

      macKey = CipherUtils.expandKey(K, H, macKey, sha, mac.getMacLength());
      macKey = CipherUtils.shrinkKey(macKey, mac.getMacLength());

      mac.init(new SecretKeySpec(macKey, macAlgorithm));
    } catch (GeneralSecurityException e) {
      cipher = null;
      mac = null;
      throw e;
    }
  }
Ejemplo n.º 12
0
 /**
  * From a password, a number of iterations and a salt, returns the corresponding digest
  *
  * @param password String The password to encrypt
  * @param salt byte[] The salt
  * @return byte[] The digested password
  * @throws NoSuchAlgorithmException If the algorithm does not exist
  * @throws UnsupportedEncodingException If the char encoding does not exist
  */
 private byte[] getHash(String password, byte[] salt)
     throws NoSuchAlgorithmException, UnsupportedEncodingException {
   MessageDigest digest = MessageDigest.getInstance("SHA-256");
   digest.reset();
   if (salt != null) {
     digest.update(salt);
   }
   byte[] input = digest.digest(password.getBytes("UTF-8"));
   for (int i = 0; i < ITERATION_NUMBER; i++) {
     digest.reset();
     input = digest.digest(input);
   }
   return input;
 }
 protected byte[] createKeyBytes(String key)
     throws UnsupportedEncodingException, NoSuchAlgorithmException {
   MessageDigest md = MessageDigest.getInstance(SECRET_KEY_HASH_TRANSFORMATION);
   md.reset();
   byte[] keyBytes = md.digest(key.getBytes(CHARSET));
   return keyBytes;
 }
Ejemplo n.º 14
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;
  }
Ejemplo n.º 15
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);
  }
  /**
   * Initialize secret key for encrypting user password
   *
   * @throws RuntimeException
   */
  private void initializeSecretKey() {
    // Random string
    String baseKey = "" + SystemClock.currentThreadTimeMillis() + new Random().nextInt();

    // md5 random string
    MessageDigest digest;
    String secretKey;
    try {
      digest = java.security.MessageDigest.getInstance("MD5");
      digest.reset();
      digest.update(baseKey.getBytes());
      byte messageDigest[] = digest.digest();
      int len = messageDigest.length;
      StringBuilder sb = new StringBuilder(len << 1);
      for (int i = 0; i < len; i++) {
        sb.append(Character.forDigit((messageDigest[i] & 0xf0) >> 4, 16));
        sb.append(Character.forDigit(messageDigest[i] & 0x0f, 16));
      }
      secretKey = sb.substring(0, 32);
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }

    // Set secret key
    this.setSecretKey(secretKey);
  }
  private String encryptFileName(String fileName) {

    Random r = new Random();
    String file[] = fileName.split("\\.");

    byte[] unencodedFile = file[0].getBytes();
    MessageDigest md = null;
    try {
      md = MessageDigest.getInstance("MD5");
    } catch (Exception e) {
    }
    md.reset();
    md.update(unencodedFile);
    byte[] encodedFile = md.digest();
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < encodedFile.length; i++) {
      if (((int) encodedFile[i] & 0xff) < 0x10) {
        buf.append("0");
      }
      buf.append(Long.toString((int) encodedFile[i] & 0xff, 16));
    }

    String encryptedFileName = (buf.toString()).concat(String.valueOf(r.nextInt()));

    return encryptedFileName + "." + file[1];
  }
Ejemplo n.º 18
0
 // MD5 password hashing
 public String md5(String value) throws NoSuchAlgorithmException {
   MessageDigest md = MessageDigest.getInstance("MD5");
   md.reset();
   md.update(value.getBytes());
   byte[] raw = md.digest();
   return new String(Base64.encode(raw));
 }
 @Override
 public List<String> getKeys() {
   String mac = getMacAddress();
   if (mac.length() != 12) {
     setErrorCode(R.string.msg_errpirelli);
     return null;
   }
   MessageDigest md;
   try {
     md = MessageDigest.getInstance("MD5");
   } catch (NoSuchAlgorithmException e1) {
     setErrorCode(R.string.msg_nomd5);
     return null;
   }
   try {
     md.reset();
     md.update(mac.toLowerCase(Locale.getDefault()).getBytes("ASCII"));
     byte[] hash = md.digest();
     String hashStr = StringUtils.getHexString(hash);
     hashStr = hashStr.substring(hashStr.length() - 16);
     addPassword(generateKey(hashStr));
     return getResults();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   return null;
 }
Ejemplo n.º 20
0
  public String newNonce(long ts) {
    // long ts=request.getTimeStamp();
    long sk = nonceSecret;

    byte[] nounce = new byte[24];
    for (int i = 0; i < 8; i++) {
      nounce[i] = (byte) (ts & 0xff);
      ts = ts >> 8;
      nounce[8 + i] = (byte) (sk & 0xff);
      sk = sk >> 8;
    }

    byte[] hash = null;
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.reset();
      md.update(nounce, 0, 16);
      hash = md.digest();
    } catch (Exception e) {
      LOG.warn(e);
    }

    for (int i = 0; i < hash.length; i++) {
      nounce[8 + i] = hash[i];
      if (i == 23) break;
    }

    return new String(B64Code.encode(nounce));
  }
  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;
    }
  }
Ejemplo n.º 22
0
  /**
   * @param wxParams 微信js接口参数
   * @throws Exception
   */
  public static void sign(WechatJsJdkParams wxParams) throws Exception {
    if (wxParams == null) {
      wxParams = new WechatJsJdkParams();
    }
    String signature = ""; // 生成最终的签名
    StringBuilder tmpStr = new StringBuilder(); // 参与签名算法的字符串汇总
    wxParams.setNoncestr(create_nonce_str());
    wxParams.setTimestamp(create_timestamp());
    // 注意这里参数名必须全部小写,且必须有序
    tmpStr.append("jsapi_ticket=");
    tmpStr.append(wxParams.getJsapiTicket());
    tmpStr.append("&noncestr=");
    tmpStr.append(wxParams.getNoncestr());
    tmpStr.append("&timestamp=");
    tmpStr.append(wxParams.getTimestamp());
    tmpStr.append("&url="); // 注意 URL 一定要动态获取,不能 hardcode
    tmpStr.append(wxParams.getSignURL());

    try {
      MessageDigest crypt = MessageDigest.getInstance("SHA-1");
      crypt.reset();
      crypt.update(tmpStr.toString().getBytes("UTF-8"));
      signature = byteToHex(crypt.digest());
    } catch (Exception e) {
      throw e;
    }
    wxParams.setSignature(signature);
  }
 /** {@inheritDoc} */
 @Override
 public byte[] addExternalFileReference(File file) throws IOException {
   byte[] sha1Bytes = null;
   final String fileName = file.getAbsolutePath();
   final MessageDigest messageDigest = this.messageDigest;
   synchronized (messageDigest) {
     messageDigest.reset();
     if (!file.exists()) {
       throw new FileNotFoundException(fileName);
     }
     final OutputStream os =
         new OutputStream() {
           public void write(int b) throws IOException {
             //
           }
         };
     final DigestOutputStream dos = new DigestOutputStream(os, messageDigest);
     calculateHash(file, dos);
     sha1Bytes = messageDigest.digest();
   }
   final File content = getExternalFileReference(sha1Bytes, true);
   final OutputStream os = new FileOutputStream(content);
   try {
     os.write(fileName.getBytes());
     os.flush();
     os.close();
   } finally {
     safeClose(os);
   }
   return sha1Bytes;
 }
Ejemplo n.º 24
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;
  }
Ejemplo n.º 25
0
  /**
   * get the md5 hash of a string
   *
   * @param str
   * @return
   */
  public static String md5(String str) {

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

    MessageDigest messageDigest = null;

    try {
      messageDigest = MessageDigest.getInstance(UpmpConfig.SIGN_TYPE);
      messageDigest.reset();
      messageDigest.update(str.getBytes(UpmpConfig.CHARSET));
    } catch (NoSuchAlgorithmException e) {

      return str;
    } catch (UnsupportedEncodingException e) {
      return str;
    }

    byte[] byteArray = messageDigest.digest();

    StringBuffer md5StrBuff = new StringBuffer();

    for (int i = 0; i < byteArray.length; i++) {
      if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
        md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
      else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
    }

    return md5StrBuff.toString();
  }
Ejemplo n.º 26
0
 public static Map<String, String> sign(String jsapi_ticket, String url) {
   Map<String, String> ret = new HashMap<String, String>();
   String nonce_str = create_nonce_str();
   String timestamp = create_timestamp();
   String str;
   String signature = "";
   str =
       "jsapi_ticket="
           + jsapi_ticket
           + "&noncestr="
           + nonce_str
           + "&timestamp="
           + timestamp
           + "&url="
           + url;
   try {
     MessageDigest crypt = MessageDigest.getInstance("SHA-1");
     crypt.reset();
     crypt.update(str.getBytes("UTF-8"));
     signature = byteToHex(crypt.digest());
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   ret.put("url", url);
   ret.put("jsapi_ticket", jsapi_ticket);
   ret.put("nonceStr", nonce_str);
   ret.put("timestamp", timestamp);
   ret.put("signature", signature);
   return ret;
 }
  // method for encryption
  public static String EncryptPassword(String passwd) {

    byte[] unencodedPassword = passwd.getBytes();
    MessageDigest md = null;

    try {
      md = MessageDigest.getInstance("MD5");
    } catch (Exception e) {
    }

    md.reset();
    md.update(unencodedPassword);

    byte[] encodedPassword = md.digest();
    StringBuffer buf = new StringBuffer();

    for (int i = 0; i < encodedPassword.length; i++) {
      if (((int) encodedPassword[i] & 0xff) < 0x10) {
        buf.append("0");
      }
      buf.append(Long.toString((int) encodedPassword[i] & 0xff, 16));
    }
    String passw = buf.toString();
    return passw;
  }
Ejemplo n.º 28
0
  private byte[] computeHash(InputStream in, long length) throws IOException {
    final MessageDigest contentDigest = state.contentDigest;
    final byte[] contentReadBuffer = state.contentReadBuffer;

    contentDigest.reset();
    contentDigest.update(hblob);
    contentDigest.update((byte) ' ');

    long sz = length;
    if (sz == 0) {
      contentDigest.update((byte) '0');
    } else {
      final int bufn = contentReadBuffer.length;
      int p = bufn;
      do {
        contentReadBuffer[--p] = digits[(int) (sz % 10)];
        sz /= 10;
      } while (sz > 0);
      contentDigest.update(contentReadBuffer, p, bufn - p);
    }
    contentDigest.update((byte) 0);

    for (; ; ) {
      final int r = in.read(contentReadBuffer);
      if (r <= 0) break;
      contentDigest.update(contentReadBuffer, 0, r);
      sz += r;
    }
    if (sz != length) return zeroid;
    return contentDigest.digest();
  }
Ejemplo n.º 29
0
  public byte[] getContentHash() {
    byte[] bytes = null;

    try {
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      ObjectOutputStream objectStream = new ObjectOutputStream(byteStream);

      objectStream.writeObject(components);
      objectStream.writeObject(pointers);
      objectStream.flush();

      bytes = byteStream.toByteArray();
    } catch (IOException ioe) {
      // too bad we don't have a good way to throw a serialziation exception
      return null;
    }

    MessageDigest md = null;
    try {
      md = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
      return null;
    }

    md.reset();
    md.update(bytes);

    return md.digest();
  }
  /**
   * Encode a string using algorithm specified in web.xml and return the resulting encrypted
   * password. If exception, the plain credentials string is returned
   *
   * @param password Password or other credentials to use in authenticating this username
   * @param algorithm Algorithm used to do the digest
   * @return encypted password based on the algorithm.
   */
  public static String encodePassword(String password, String algorithm) {
    byte[] unencodedPassword = password.getBytes();

    MessageDigest md = null;

    try {
      // first create an instance, given the provider
      md = MessageDigest.getInstance(algorithm);
    } catch (Exception e) {
      log.error("Exception: " + e);
      return password;
    }

    md.reset();
    md.update(unencodedPassword);

    // now calculate the hash
    byte[] encodedPassword = md.digest();
    StringBuffer buf = new StringBuffer();

    for (int i = 0; i < encodedPassword.length; i++) {
      if (((int) encodedPassword[i] & 0xff) < 0x10) {
        buf.append("0");
      }
      buf.append(Long.toString((int) encodedPassword[i] & 0xff, 16));
    }
    return buf.toString();
  }