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;
  }
Esempio n. 2
0
 public static int getColorIndex(int id) {
   int[] arr;
   if (id >= 0) {
     arr = arrUsersAvatars;
   } else {
     arr = arrGroupsAvatars;
   }
   try {
     String str;
     if (id >= 0) {
       str = String.format(Locale.US, "%d%d", id, UserConfig.clientUserId);
     } else {
       str = String.format(Locale.US, "%d", id);
     }
     if (str.length() > 15) {
       str = str.substring(0, 15);
     }
     java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
     byte[] digest = md.digest(str.getBytes());
     int b = digest[Math.abs(id % 16)];
     if (b < 0) {
       b += 256;
     }
     return Math.abs(b) % arr.length;
   } catch (Exception e) {
     FileLog.e("tmessages", e);
   }
   return id % arr.length;
 }
  // MD5加密,32位
  public static String MD5(String str) {
    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
    } catch (Exception e) {
      e.printStackTrace();
      return "";
    }

    char[] charArray = str.toCharArray();
    byte[] byteArray = new byte[charArray.length];

    for (int i = 0; i < charArray.length; i++) {
      byteArray[i] = (byte) charArray[i];
    }
    byte[] md5Bytes = md5.digest(byteArray);

    StringBuffer hexValue = new StringBuffer();
    for (int i = 0; i < md5Bytes.length; i++) {
      int val = ((int) md5Bytes[i]) & 0xff;
      if (val < 16) {
        hexValue.append("0");
      }
      hexValue.append(Integer.toHexString(val));
    }
    return hexValue.toString();
  }
Esempio n. 4
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();
  }
  private String obfuscate(String data) {
    if (data == null || data.length() <= 0) {
      return null;
    }

    MessageDigest digest;
    try {
      digest = MessageDigest.getInstance("MD5"); // $NON-NLS-1$
    } catch (NoSuchAlgorithmException ex) {
      try {
        digest = MessageDigest.getInstance("SHA"); // $NON-NLS-1$
      } catch (NoSuchAlgorithmException ex1) {
        return "***"; //$NON-NLS-1$
      }
    }
    digest.update(data.getBytes());
    byte messageDigest[] = digest.digest();
    StringBuilder hexString = new StringBuilder(64);
    for (int i = 0; i < messageDigest.length; i++) {
      String hex = Integer.toHexString(0xFF & messageDigest[i]);
      if (hex.length() == 1) {
        hexString.append('0');
      }
      hexString.append(hex);
    }
    return hexString.toString();
  }
Esempio n. 6
0
  public static String getFileMD5(File file) {
    if (!file.isFile()) {
      return null;
    }
    MessageDigest digest = null;
    FileInputStream in = null;
    byte buffer[] = new byte[1024];
    int len;
    try {
      digest = MessageDigest.getInstance("MD5");
      in = new FileInputStream(file);
      while ((len = in.read(buffer, 0, 1024)) != -1) {
        digest.update(buffer, 0, len);
      }
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    BigInteger bigInt = new BigInteger(1, digest.digest());

    String md5Value = bigInt.toString(16);
    if (md5Value.length() < 32) {
      for (int i = 0; i < 32 - md5Value.length(); i++) {
        md5Value = "0" + md5Value;
      }
    }
    return md5Value.toLowerCase();
  }
Esempio n. 7
0
 public static final String MD5(String s) {
   char hexDigits[] = {
     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
   };
   try {
     byte[] btInput = s.getBytes();
     // 获得MD5摘要算法的 MessageDigest 对象
     MessageDigest mdInst = MessageDigest.getInstance("MD5");
     // 使用指定的字节更新摘要
     mdInst.update(btInput);
     // 获得密文
     byte[] md = mdInst.digest();
     // 把密文转换成十六进制的字符串形式
     int j = md.length;
     char str[] = new char[j * 2];
     int k = 0;
     for (int i = 0; i < j; i++) {
       byte byte0 = md[i];
       str[k++] = hexDigits[byte0 >>> 4 & 0xf];
       str[k++] = hexDigits[byte0 & 0xf];
     }
     return new String(str);
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Esempio n. 8
0
 public static String getMD5(File file) {
   FileInputStream fileInputStream = null;
   try {
     MessageDigest md = MessageDigest.getInstance("MD5");
     fileInputStream = new FileInputStream(file);
     byte[] buffer = new byte[2048];
     int length = -1;
     long s = System.currentTimeMillis();
     while ((length = fileInputStream.read(buffer)) != -1) {
       md.update(buffer, 0, length);
     }
     byte[] b = md.digest();
     return byteToHexString(b);
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
     return null;
   } catch (FileNotFoundException e) {
     e.printStackTrace();
     return null;
   } catch (IOException e) {
     e.printStackTrace();
     return null;
   } finally {
     try {
       fileInputStream.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Esempio n. 9
0
  /** 对字符串进行MD5编码,32位 */
  public static String MD5Encoding(String inStr) {
    if (inStr == null || inStr.isEmpty()) {
      return null;
    }

    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
    } catch (Exception e) {
      System.out.println(e.toString());
      e.printStackTrace();
      return "";
    }
    char[] charArray = inStr.toCharArray();
    byte[] byteArray = new byte[charArray.length];
    for (int i = 0; i < charArray.length; i++) byteArray[i] = (byte) charArray[i];
    byte[] md5Bytes = md5.digest(byteArray);
    StringBuffer hexValue = new StringBuffer();
    for (int i = 0; i < md5Bytes.length; i++) {
      int val = ((int) md5Bytes[i]) & 0xff;
      if (val < 16) hexValue.append("0");
      hexValue.append(Integer.toHexString(val));
    }
    return hexValue.toString();
  }
Esempio n. 10
0
  public static String getFileMd5(String sourceDir) {
    try {
      File file = new File(sourceDir);
      FileInputStream fis = new FileInputStream(file);
      byte[] buf = new byte[1024];
      int len = -1;

      // 获取数字摘要
      MessageDigest messageDigest = MessageDigest.getInstance("MD5");
      while ((len = fis.read(buf)) != -1) {
        messageDigest.update(buf, 0, len);
      }
      byte[] result = messageDigest.digest();
      StringBuffer sb = new StringBuffer();
      for (byte b : result) {
        int i = b & 0xff;
        String hexString = Integer.toHexString(i);
        if (hexString.length() < 2) {
          hexString = "0" + hexString;
        }
        sb.append(hexString);
      }
      return sb.toString();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    return null;
  }
Esempio n. 11
0
 public static String sha1Hash(String filePath) {
   try {
     MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
     FileInputStream fileInputStream = new FileInputStream(filePath);
     byte[] dataBytes = new byte[1024];
     int nread = 0;
     while ((nread = fileInputStream.read(dataBytes)) != -1) {
       messageDigest.update(dataBytes, 0, nread);
     }
     ;
     fileInputStream.close();
     byte[] mdbytes = messageDigest.digest();
     StringBuffer stringBuilder = new StringBuffer("");
     for (int i = 0; i < mdbytes.length; i++) {
       stringBuilder.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
     }
     return stringBuilder.toString();
   } catch (NoSuchAlgorithmException e) {
     RfcxLog.logExc(logTag, e);
   } catch (FileNotFoundException e) {
     RfcxLog.logExc(logTag, e);
   } catch (IOException e) {
     RfcxLog.logExc(logTag, e);
   } catch (Exception e) {
     RfcxLog.logExc(logTag, e);
   }
   return null;
 }
 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;
 }
  /**
   * Computes the SHA-1 hash value of the input string's UTF-8 representation and returns the first
   * numBits bits of the result as a hex value in string form.
   *
   * @param strToHash The string to compute SHA-1 of.
   * @param numBits The number of bits worth to return. Must be a positive number at most 160 and
   *     divisible by 8 (since we process the result 8 bits at a time).
   * @return The partial SHA-1 hash value as a hex string.
   */
  public static String computePartialSha1AsHexString(String strToHash, int numBits) {

    Preconditions.checkArgument(numBits > 0 && numBits <= 160 && numBits % 8 == 0);
    int numBytes = numBits / 8;

    byte[] digestBytes;
    try {
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      digestBytes = md.digest(strToHash.getBytes("UTF-8"));
    } catch (NoSuchAlgorithmException e) {
      throw new AssertionError("Java should always have SHA-1.");
    } catch (UnsupportedEncodingException e) {
      throw new AssertionError("Java should always have UTF-8.");
    }

    StringBuilder digestHexBuilder = new StringBuilder();
    for (int i = 0; i < numBytes; i++) {
      byte digestByte = digestBytes[i];
      String digestByteHex = Integer.toHexString(0xFF & digestByte);
      if (digestByteHex.length() == 1) {
        digestByteHex = "0" + digestByteHex; // pad to 2 digits
      }
      digestHexBuilder.append(digestByteHex);
    }
    return digestHexBuilder.toString();
  }
Esempio n. 14
0
 public static String SHA1(String text)
     throws NoSuchAlgorithmException, UnsupportedEncodingException {
   MessageDigest md = MessageDigest.getInstance("SHA-1");
   md.update(text.getBytes("iso-8859-1"), 0, text.length());
   byte[] sha1hash = md.digest();
   return convertToHex(sha1hash);
 }
Esempio n. 15
0
 private String getFileMD5String(File file, int bufferSize) {
   FileInputStream fileInputStream = null;
   byte[] buffer = new byte[bufferSize];
   try {
     MessageDigest targetMD5 = MessageDigest.getInstance("MD5");
     fileInputStream = new FileInputStream(file);
     int len;
     while ((len = fileInputStream.read(buffer)) != -1) {
       targetMD5.update(buffer, 0, len);
     }
     return DataSwitch.bytesToHexString(targetMD5.digest()).toUpperCase();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } finally {
     if (fileInputStream != null)
       try {
         fileInputStream.close();
       } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
   }
   return null;
 }
 static String getThumbPrint(final byte[] der)
     throws NoSuchAlgorithmException, CertificateEncodingException {
   final MessageDigest md = MessageDigest.getInstance("SHA-1");
   md.update(der);
   final byte[] digest = md.digest();
   return hexify(digest);
 }
Esempio n. 17
0
  private MessageDigest setSHA1(AuthSecrets macParms) {
    try {
      mySHA1 = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
      Trace.comm.errorm(" Unable to build SHA", e);
      Trace.comm.notifyFatal();
    }
    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      Trace.comm.errorm("Unable to build MD5", e);
      Trace.comm.notifyFatal();
    }
    // Calculate the MAC key
    byte[] macKey = new byte[64];
    System.arraycopy(md5Hash(0x11, macParms.myDHSecret, md5), 0, macKey, 0, 16);
    System.arraycopy(md5Hash(0x22, macParms.myDHSecret, md5), 0, macKey, 16, 16);
    System.arraycopy(md5Hash(0x33, macParms.myDHSecret, md5), 0, macKey, 32, 16);
    System.arraycopy(md5Hash(0x44, macParms.myDHSecret, md5), 0, macKey, 48, 16);
    myMACKey = macParms.myMacKey = macKey;

    // Set up to do the MAC calculation
    myIsDoingMac = true;
    myMAC = new byte[20];
    return md5;
  }
Esempio n. 18
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();
  }
Esempio n. 19
0
  public StringBuffer CheckSum(String source) throws NoSuchAlgorithmException, IOException {
    // MessageDigest md = MessageDigest.getInstance("MD5");
    // Change MD5 to SHA1 to get SHA checksum
    MessageDigest md = MessageDigest.getInstance("SHA1");

    FileInputStream fis = new FileInputStream(source);
    byte[] dataBytes = new byte[4096];
    int nread = 0;

    while ((nread = fis.read(dataBytes)) != -1) {
      md.update(dataBytes, 0, nread);
    }
    ;

    byte[] mdbytes = md.digest();

    // convert the byte to hex format
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < mdbytes.length; i++) {
      sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }

    //  System.out.println("Checksum");

    //  System.out.println(sb.toString() + " " + source);

    //    System.out.println("------------------");
    fis.close();

    return sb;
  }
  // 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;
  }
 @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;
 }
  /**
   * Computes the sha1 of a file and returns it.
   *
   * @param f the file to compute the sha1 for.
   * @return the sha1 value
   * @throws Sha1Exception if the sha1 value cannot be computed.
   */
  private static String getSha1(File f) throws Sha1Exception {
    synchronized (sBuffer) {
      FileInputStream fis = null;
      try {
        MessageDigest md = MessageDigest.getInstance("SHA-1");

        fis = new FileInputStream(f);
        while (true) {
          int length = fis.read(sBuffer);
          if (length > 0) {
            md.update(sBuffer, 0, length);
          } else {
            break;
          }
        }

        return byteArray2Hex(md.digest());

      } catch (Exception e) {
        throw new Sha1Exception(f, e);
      } finally {
        if (fis != null) {
          try {
            fis.close();
          } catch (IOException e) {
            // ignore
          }
        }
      }
    }
  }
Esempio n. 23
0
  public static void verifyMD5(File file, String originalMd5) throws Exception {
    log.info("M-READ file:" + file);
    MessageDigest md = MessageDigest.getInstance("MD5");

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));

    DigestInputStream dis = new DigestInputStream(in, md);
    try {
      DcmParser parser = DcmParserFactory.getInstance().newDcmParser(dis);
      parser.parseDcmFile(FileFormat.DICOM_FILE, Tags.PixelData);
      if ((parser.getReadTag() & 0xFFFFFFFFL) >= Tags.PixelData) {
        if (parser.getReadLength() == -1) {
          while (parser.parseHeader() == Tags.Item) {
            readOut(parser.getInputStream(), parser.getReadLength());
          }
        }
        readOut(parser.getInputStream(), parser.getReadLength());
        parser.parseDataset(parser.getDcmDecodeParam(), -1);
      }
    } finally {
      try {
        dis.close();
      } catch (IOException ignore) {
      }
    }
    byte[] md5 = md.digest();
    if (!Arrays.equals(md5, MD5.toBytes(originalMd5))) {
      log.error(
          "MD5 for "
              + file.getAbsolutePath()
              + " is different that expected.  Has the file been changed or corrupted?");
      throw new IllegalStateException("MD5 mismatch");
    }
  }
Esempio n. 24
0
  public static String crypt(String str) {
    if (str == null || str.length() == 0) {
      throw new IllegalArgumentException("String to encrypt cannot be null or zero length");
    }

    StringBuffer hexString = new StringBuffer();

    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(str.getBytes());
      byte[] hash = md.digest();

      for (int i = 0; i < hash.length; i++) {
        if ((0xff & hash[i]) < 0x10) {
          hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
        } else {
          hexString.append(Integer.toHexString(0xFF & hash[i]));
        }
      }
    } catch (NoSuchAlgorithmException e) {

    }

    return hexString.toString();
  }
Esempio n. 25
0
  public static String md5(String plainText) {
    String str;
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(plainText.getBytes());
      byte b[] = md.digest();

      int i;

      StringBuffer buf = new StringBuffer("");
      for (int offset = 0; offset < b.length; offset++) {
        i = b[offset];
        if (i < 0) i += 256;
        if (i < 16) buf.append("0");
        buf.append(Integer.toHexString(i));
      }
      str = buf.toString();
      // System.out.println("result: " + buf.toString());// 32位的加密
      // System.out.println("result: " + buf.toString().substring(8,
      // 24));// 16位的加密
      return str;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    return null;
  }
 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());
   }
 }
Esempio n. 27
0
  public static boolean isAuthenticated(String username, String connectionHash, SecretKey shared)
      throws NoSuchAlgorithmException, IOException {
    String encName = URLEncoder.encode(username, "UTF-8");

    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    for (byte[] bit :
        new byte[][] {
          connectionHash.getBytes("ISO_8859_1"), shared.getEncoded(), keys.getPublic().getEncoded()
        }) {
      sha.update(bit);
    }

    String encodedHash = URLEncoder.encode(new BigInteger(sha.digest()).toString(16), "UTF-8");
    String authURL =
        "http://session.minecraft.net/game/checkserver.jsp?user="******"&serverId="
            + encodedHash;
    String reply;
    try (BufferedReader in =
        new BufferedReader(new InputStreamReader(new URL(authURL).openStream()))) {
      reply = in.readLine();
    }

    return "YES".equals(reply);
  }
 private static void appendList(MessageDigest digest, List<?> value) {
   digest.update("L".getBytes());
   for (Object object : value) {
     appendObject(digest, object);
     digest.update(",".getBytes());
   }
 }
Esempio n. 29
0
  /**
   * * Login to the POP3 server with the given username and authentication information. Use this
   * method when connecting to a server requiring authentication using the APOP command. Because the
   * timestamp produced in the greeting banner varies from server to server, it is not possible to
   * consistently extract the information. Therefore, after connecting to the server, you must call
   * {@link org.apache.commons.net.pop3.POP3#getReplyString getReplyString } and parse out the
   * timestamp information yourself.
   *
   * <p>You must first connect to the server with {@link org.apache.commons.net.SocketClient#connect
   * connect } before attempting to login. A login attempt is only valid if the client is in the
   * {@link org.apache.commons.net.pop3.POP3#AUTHORIZATION_STATE AUTHORIZATION_STATE } . After
   * logging in, the client enters the {@link org.apache.commons.net.pop3.POP3#TRANSACTION_STATE
   * TRANSACTION_STATE } . After connecting, you must parse out the server specific information to
   * use as a timestamp, and pass that information to this method. The secret is a shared secret
   * known to you and the server. See RFC 1939 for more details regarding the APOP command.
   *
   * <p>
   *
   * @param username The account name being logged in to.
   * @param timestamp The timestamp string to combine with the secret.
   * @param secret The shared secret which produces the MD5 digest when combined with the timestamp.
   * @return True if the login attempt was successful, false if not.
   * @exception IOException If a network I/O error occurs in the process of logging in.
   * @exception NoSuchAlgorithmException If the MD5 encryption algorithm cannot be instantiated by
   *     the Java runtime system. *
   */
  public boolean login(String username, String timestamp, String secret)
      throws IOException, NoSuchAlgorithmException {
    int i;
    byte[] digest;
    StringBuffer buffer, digestBuffer;
    MessageDigest md5;

    if (getState() != AUTHORIZATION_STATE) return false;

    md5 = MessageDigest.getInstance("MD5");
    timestamp += secret;
    digest = md5.digest(timestamp.getBytes());
    digestBuffer = new StringBuffer(128);

    for (i = 0; i < digest.length; i++) digestBuffer.append(Integer.toHexString(digest[i] & 0xff));

    buffer = new StringBuffer(256);
    buffer.append(username);
    buffer.append(' ');
    buffer.append(digestBuffer.toString());

    if (sendCommand(POP3Command.APOP, buffer.toString()) != POP3Reply.OK) return false;

    setState(TRANSACTION_STATE);

    return true;
  }
Esempio n. 30
0
  public static String getDigestHashOldFunnyHexEncode(String str, String hashType) {
    if (UtilValidate.isEmpty(hashType)) hashType = "SHA";
    if (str == null) return null;
    try {
      MessageDigest messagedigest = MessageDigest.getInstance(hashType);
      byte strBytes[] = str.getBytes();

      messagedigest.update(strBytes);
      byte digestBytes[] = messagedigest.digest();
      int k = 0;
      char digestChars[] = new char[digestBytes.length * 2];

      for (int l = 0; l < digestBytes.length; l++) {
        int i1 = digestBytes[l];

        if (i1 < 0) {
          i1 = 127 + i1 * -1;
        }
        StringUtil.encodeInt(i1, k, digestChars);
        k += 2;
      }

      return new String(digestChars, 0, digestChars.length);
    } catch (Exception e) {
      logger.error("Error while computing hash of type " + hashType, e);
    }
    return str;
  }