Java Code Examples for java.security.MessageDigest#getInstance()

The following examples show how to use java.security.MessageDigest#getInstance() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: imsdk-android   File: MD5Util.java    License: MIT License 6 votes vote down vote up
/**
 * MD5加密
 *
 * @param origin 字符
 * @param charsetName 编码
 */
public static String md5Encode(String origin, String charsetName) {
    String resultString = null;
    try {
        resultString = origin;
        MessageDigest md = MessageDigest.getInstance("MD5");
        if (null == charsetName || "".equals(charsetName)) {
            resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
        } else {
            resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetName)));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultString;
}
 
Example 2
Source Project: arcusplatform   File: Crypto.java    License: Apache License 2.0 6 votes vote down vote up
public static long benchmarkMessageDigest(String algorithm, int blocks, @Nullable String provider) throws Exception {
   byte[] data = getRandomData(1024);

   MessageDigest md;
   if (provider == null) {
      md = MessageDigest.getInstance(algorithm);
   } else {
      md = MessageDigest.getInstance(algorithm, provider);
   }

   long start = System.nanoTime();
   for (int i = 0; i < blocks; ++i) {
      md.update(data);
   }

   md.digest();
   return System.nanoTime() - start;
}
 
Example 3
Source Project: apollo   File: Encryptor.java    License: Apache License 2.0 6 votes vote down vote up
public static String encryptString(String string) {

        // Create MessageDigest instance for MD5
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("MD5");
            digest.update(string.getBytes());

            byte[] bytes = digest.digest();

            //This bytes[] has bytes in decimal format;
            //Convert it to hexadecimal format
            StringBuilder sb = new StringBuilder();
            for (byte aByte : bytes) {
                sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
            }

            //Get complete hashed password in hex format
            return sb.toString();

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Could not find algorithm MD5!", e);
        }
    }
 
Example 4
/**
    * <p>
 * This method hashes a clear user password using a
 * Single Hash algorithm such as SHA-1 (SHA equivalent)
 * (it is a 160 bits digest)
    * </p>
 *
    * <p>
 * The digest is returned as an object string.
    * </p>
    *
    * <p>
    * This method is only used by the SHA-1 authentication scheme.
    * </p>
 *
 * @param plainTxtUserPassword Plain text user password
 *
 * @return hashed user password (digest) as a String object
    *         or {@code null} if the plaintext password is {@code null}
 */
protected String hashPasswordSHA1Scheme(String plainTxtUserPassword)
{
	if (plainTxtUserPassword == null)
		return null;

	MessageDigest algorithm = null;
	try
	{
		algorithm = MessageDigest.getInstance("SHA-1");
	} catch (NoSuchAlgorithmException nsae)
	{
				// Ignore as we checked already during service boot-up
	}

	algorithm.reset();
	byte[] bytePasswd = null;
       bytePasswd = toHexByte(plainTxtUserPassword);
	algorithm.update(bytePasswd);
	byte[] hashedVal = algorithm.digest();
	return (PasswordHasher.ID_PATTERN_SHA1_SCHEME +
               StringUtil.toHexString(hashedVal, 0, hashedVal.length));

}
 
Example 5
String getValue(JetstreamEvent event) {
	
	MessageDigest md;
	try {
		md = MessageDigest.getInstance("MD5");
	} 
	catch (NoSuchAlgorithmException e) {
		throw new RuntimeException(e);
	}
	for (String strField : m_aFields) {
		Object objValue = event.get(strField);
		if (objValue != null)
			md.update(objValue.toString().getBytes());
	}
	BigInteger bi = new BigInteger(1, md.digest());
	return bi.toString(16);
}
 
Example 6
Source Project: erp-framework   File: Digests.java    License: MIT License 6 votes vote down vote up
private static byte[] digest(InputStream input, String algorithm) throws IOException {
	try {
		MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
		int bufferLength = 8 * 1024;
		byte[] buffer = new byte[bufferLength];
		int read = input.read(buffer, 0, bufferLength);

		while (read > -1) {
			messageDigest.update(buffer, 0, read);
			read = input.read(buffer, 0, bufferLength);
		}

		return messageDigest.digest();
	} catch (GeneralSecurityException e) {
		throw Exceptions.unchecked(e);
	}
}
 
Example 7
public static void main(String[] args) throws Exception {

        X509CertImpl cert = loadCert(CERT_FILENAME);

        /* Compute the hash in the same way as CertId constructor */
        MessageDigest hash = MessageDigest.getInstance("SHA1");
        hash.update(cert.getSubjectX500Principal().getEncoded());
        byte[] expectedHash = hash.digest();

        CertId certId = new CertId(cert, null);
        byte[] receivedHash = certId.getIssuerNameHash();

        if (! Arrays.equals(expectedHash, receivedHash)) {
            throw new
                Exception("Bad hash value for issuer name in CertId object");
        }
    }
 
Example 8
Source Project: HttpRequest   File: MD5Util.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * md5 encode
 * @author leibing
 * @createTime 2017/5/6
 * @lastModify 2017/5/6
 * @param origin 原字符串
 * @param charsetname 字符格式
 * @return
 */
public static String md5Encode(String origin, String charsetname) {
	String resultString = null;
	try {
		resultString = new String(origin);
		MessageDigest md = MessageDigest.getInstance("MD5");
		if (charsetname == null || "".equals(charsetname))
			resultString = byteArrayToHexString(md.digest(resultString
					.getBytes()));
		else
			resultString = byteArrayToHexString(md.digest(resultString
					.getBytes(charsetname)));
	} catch (Exception exception) {
	}
	return resultString;
}
 
Example 9
Source Project: XKnife-Android   File: DeviceUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 将签名字符串转换成需要的32位签名
 */
private static String hexdigest(byte[] paramArrayOfByte) {
    final char[] hexDigits = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97,
            98, 99, 100, 101, 102};
    try {
        MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
        localMessageDigest.update(paramArrayOfByte);
        byte[] arrayOfByte = localMessageDigest.digest();
        char[] arrayOfChar = new char[32];
        for (int i = 0, j = 0; ; i++, j++) {
            if (i >= 16) {
                return new String(arrayOfChar);
            }
            int k = arrayOfByte[i];
            arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
            arrayOfChar[++j] = hexDigits[(k & 0xF)];
        }
    } catch (Exception e) {
    }
    return "";
}
 
Example 10
/**
 * Write the signature file to the given output stream.
 */
private void generateSignatureFile(Manifest manifest, OutputStream out)
        throws IOException, GeneralSecurityException {
    out.write(("Signature-Version: 1.0\r\n").getBytes());
    out.write(("Created-By: 1.0 (Android SignApk)\r\n").getBytes());


    // BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance("SHA1");
    PrintStream print = new PrintStream(
            new DigestOutputStream(new ByteArrayOutputStream(), md),
            true, "UTF-8");

    // Digest of the entire manifest
    manifest.write(print);
    print.flush();

    out.write(("SHA1-Digest-Manifest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes());

    Map<String, Attributes> entries = manifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
        if (canceled) break;
        progressHelper.progress(ProgressEvent.PRORITY_NORMAL, resourceAdapter.getString(ResourceAdapter.Item.GENERATING_SIGNATURE_FILE));
        // Digest of the manifest stanza for this entry.
        String nameEntry = "Name: " + entry.getKey() + "\r\n";
        print.print(nameEntry);
        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();

        out.write(nameEntry.getBytes());
        out.write(("SHA1-Digest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes());
    }

}
 
Example 11
Source Project: bitseal   File: SHA512.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
* Calculates the SHA-512 hash of the given byte range, and then hashes the resulting hash again. This is
   * standard procedure in BitCoin. The resulting hash is in big endian form.
* 
* @param input - A byte[] containing the data to hash
* @param offset - An int representing the index in the data byte[] at which to begin
* @param length - An int representing the number of bytes from the data byte[] to process
* 
* @return A byte[] containing the doubly SHA-512 hashed data
*/
  public static byte[] doubleHash(byte[] input, int offset, int length) 
  {
      try 
      {
          MessageDigest digest = MessageDigest.getInstance("SHA-512");
          digest.update(input, offset, length);
          byte[] first = digest.digest();
          return digest.digest(first);
      } 
      catch (NoSuchAlgorithmException e) 
      {
      	throw new RuntimeException("NoSuchAlgorithmException occurred in DigestSHA512.doubleDigest()", e);
      }
  }
 
Example 12
public static 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).toLowerCase();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 13
Source Project: admin-plus   File: MD5Util.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取十六进制字符串形式的MD5摘要
 */
private static String md5Hex(String src) {
	try {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		byte[] bs = md5.digest(src.getBytes());
		return new String(new Hex().encode(bs));
	} catch (Exception e) {
		return null;
	}
}
 
Example 14
/**
 * Initializes a new instance of the BlobOutputStream class.
 * 
 * @param parentBlob
 *            A {@link CloudBlob} object which represents the blob that this stream is associated with.
 * @param accessCondition
 *            An {@link AccessCondition} object which represents the access conditions for the blob.
 * @param options
 *            A {@link BlobRequestOptions} object which specifies any additional options for the request.
 * @param opContext
 *            An {@link OperationContext} object which is used to track the execution of the operation.
 * 
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
private BlobOutputStream(final CloudBlob parentBlob, final AccessCondition accessCondition,
        final BlobRequestOptions options, final OperationContext opContext) throws StorageException {
    this.accessCondition = accessCondition;
    this.parentBlobRef = parentBlob;
    this.parentBlobRef.assertCorrectBlobType();
    this.options = new BlobRequestOptions(options);
    this.outBuffer = new ByteArrayOutputStream();
    this.opContext = opContext;

    if (this.options.getConcurrentRequestCount() < 1) {
        throw new IllegalArgumentException("ConcurrentRequestCount");
    }
    
    this.futureSet = Collections.newSetFromMap(new ConcurrentHashMap<Future<Void>, Boolean>(
            this.options.getConcurrentRequestCount() == null ? 1 : this.options.getConcurrentRequestCount() * 2));

    if (this.options.getStoreBlobContentMD5()) {
        try {
            this.md5Digest = MessageDigest.getInstance("MD5");
        }
        catch (final NoSuchAlgorithmException e) {
            // This wont happen, throw fatal.
            throw Utility.generateNewUnexpectedStorageException(e);
        }
    }

    // V2 cachedThreadPool for perf.        
    this.threadExecutor = new ThreadPoolExecutor(
            this.options.getConcurrentRequestCount(),
            this.options.getConcurrentRequestCount(),
            10, 
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());
    this.completionService = new ExecutorCompletionService<Void>(this.threadExecutor);
}
 
Example 15
Source Project: Rumble   File: HashUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static final String computeStatusUUID(String author_uid, String group_gid, String post, long timeOfCreation) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(author_uid.getBytes());
        md.update(group_gid.getBytes());
        md.update(post.getBytes());
        md.update(ByteBuffer.allocate(8).putLong(timeOfCreation).array());
        return Base64.encodeToString(md.digest(),0, PushStatus.STATUS_ID_RAW_SIZE,Base64.NO_WRAP);
    }
    catch (NoSuchAlgorithmException ignore) {
        return null;
    }
}
 
Example 16
/**
 * Hash the specified sequence of bytes
 *
 * @param data the data to hash
 * @return the digest value
 */
public static byte[] hash(byte[]... data) {
    try {
        MessageDigest h = MessageDigest.getInstance(HASH_ALGORITHM);
        for (byte[] d : data) {
            h.update(d);
        }
        return h.digest();
    }
    catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("The hash algorithm " + HASH_ALGORITHM + " is not available", e);
    }
}
 
Example 17
Source Project: gocd   File: ServerBinaryDownloaderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetMd5AndSSLPortHeaders() throws Exception {
    ServerBinaryDownloader downloader = new ServerBinaryDownloader(new GoAgentServerHttpClientBuilder(null, SslVerificationMode.NONE, null, null, null), ServerUrlGeneratorMother.generatorFor("localhost", server.getPort()));
    downloader.downloadIfNecessary(DownloadableFile.AGENT);

    MessageDigest digester = MessageDigest.getInstance("MD5");
    try (BufferedInputStream stream = new BufferedInputStream(new FileInputStream(DownloadableFile.AGENT.getLocalFile()))) {
        try (DigestInputStream digest = new DigestInputStream(stream, digester)) {
            IOUtils.copy(digest, new NullOutputStream());
        }
        assertThat(downloader.getMd5(), is(Hex.encodeHexString(digester.digest()).toLowerCase()));
    }
}
 
Example 18
Source Project: hasor   File: DigestUdfSource.java    License: Apache License 2.0 5 votes vote down vote up
/** 使用指定方式进行摘要计算 */
public static byte[] digestString(DigestType digestType, String content) throws NoSuchAlgorithmException {
    if (content == null) {
        return null;
    }
    MessageDigest mdTemp = MessageDigest.getInstance(digestType.getDigestDesc());
    mdTemp.update(content.getBytes());
    return mdTemp.digest();
}
 
Example 19
private String computeDigest(
                    boolean isRequest, String userName, char[] password,
                    String realm, String connMethod,
                    String requestURI, String nonceString,
                    String cnonce, String ncValue
                ) throws NoSuchAlgorithmException
{

    String A1, HashA1;
    String algorithm = params.getAlgorithm ();
    boolean md5sess = algorithm.equalsIgnoreCase ("MD5-sess");

    MessageDigest md = MessageDigest.getInstance(md5sess?"MD5":algorithm);

    if (md5sess) {
        if ((HashA1 = params.getCachedHA1 ()) == null) {
            String s = userName + ":" + realm + ":";
            String s1 = encode (s, password, md);
            A1 = s1 + ":" + nonceString + ":" + cnonce;
            HashA1 = encode(A1, null, md);
            params.setCachedHA1 (HashA1);
        }
    } else {
        A1 = userName + ":" + realm + ":";
        HashA1 = encode(A1, password, md);
    }

    String A2;
    if (isRequest) {
        A2 = connMethod + ":" + requestURI;
    } else {
        A2 = ":" + requestURI;
    }
    String HashA2 = encode(A2, null, md);
    String combo, finalHash;

    if (params.authQop()) { /* RRC2617 when qop=auth */
        combo = HashA1+ ":" + nonceString + ":" + ncValue + ":" +
                    cnonce + ":auth:" +HashA2;

    } else { /* for compatibility with RFC2069 */
        combo = HashA1 + ":" +
                   nonceString + ":" +
                   HashA2;
    }
    finalHash = encode(combo, null, md);
    return finalHash;
}
 
Example 20
Source Project: java-unified-sdk   File: MD5.java    License: Apache License 2.0 4 votes vote down vote up
private MD5() {
  try {
    mdInstance = MessageDigest.getInstance("MD5");
  } catch (NoSuchAlgorithmException ex) {
  }
}