java.security.MessageDigest Java Examples

The following examples show how to use java.security.MessageDigest. 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 File: RangerKeyStore.java    From ranger with Apache License 2.0 6 votes vote down vote up
private MessageDigest getKeyedMessageDigest(char[] aKeyPassword)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    int i, j;

    MessageDigest md = MessageDigest.getInstance("SHA");
    byte[] keyPasswordBytes = new byte[aKeyPassword.length * 2];
    for (i = 0, j = 0; i < aKeyPassword.length; i++) {
        keyPasswordBytes[j++] = (byte) (aKeyPassword[i] >> 8);
        keyPasswordBytes[j++] = (byte) aKeyPassword[i];
    }
    md.update(keyPasswordBytes);
    for (i = 0; i < keyPasswordBytes.length; i++)
        keyPasswordBytes[i] = 0;
    md.update(SECRET_KEY_HASH_WORD.getBytes("UTF8"));
    return md;
}
 
Example #2
Source File: Crypt.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
private static String encode(final String s, final String alg)
{
  try {
    final MessageDigest md = MessageDigest.getInstance(alg);
    md.reset();
    md.update(s.getBytes());
    final byte[] d = md.digest();

    String ret = "";

    for (int val : d) {
      final char[] hex = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
      if (val < 0) {
        val = 256 + val;
      }
      final char hi = hex[val / 16];
      final char lo = hex[val % 16];
      ret = hi + "" + lo + ret;
    }
    return md.getAlgorithm() + '{' + ret + '}';
  } catch (final NoSuchAlgorithmException ex) {
    log.fatal(ex);
    return "NONE{" + s + "}";
  }
}
 
Example #3
Source File: ShardStrategyFactory.java    From moleculer-java with MIT License 6 votes vote down vote up
@Override
public Long apply(String key) {
	byte[] bytes = key.getBytes(StandardCharsets.UTF_8);
	MessageDigest hasher = hashers.get();
	if (hasher == null) {
		try {
			hasher = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException notFound) {
			throw new RuntimeException(notFound);
		}
		hashers.set(hasher);
	}
	hasher.update(bytes);
	byte[] md5Bytes = hasher.digest();
	char[] hexChars = new char[md5Bytes.length * 2];
	for (int j = 0; j < md5Bytes.length; j++) {
		int v = md5Bytes[j] & 0xFF;
		hexChars[j * 2] = HEX[v >>> 4];
		hexChars[j * 2 + 1] = HEX[v & 0x0F];
	}
	String hexString = new String(hexChars);
	if (hexString.length() > 8) {
		hexString = hexString.substring(0, 8);
	}
	return Long.parseLong(hexString, 16);
}
 
Example #4
Source File: CoreControllerHelp.java    From JavaWeb with Apache License 2.0 6 votes vote down vote up
/**
URL(服务器地址) http://www.programself.com/JavaWeb/app/weichat/core/accessWeiChat
Token(令牌) pirtzxLSjoAjacYXemOSflqtyns0wpQK
EncodingAESKey(消息加解密密钥) xcd4N4i53IB9rrtLOra7Tvt8ybLLhAzjacKhGBaUb7h
消息加解密方式 安全模式
*/

//校验签名
public static boolean checkSignature(String signature, String timestamp, String nonce) throws Exception {
	//将token、timestamp、nonce三个参数进行字典序排序
	String[] paramArr = new String[] { Token, timestamp, nonce };
	Arrays.sort(paramArr);
	//将三个参数字符串拼接成一个字符串进行sha1加密
	String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
	MessageDigest md = MessageDigest.getInstance("SHA-1");
	// 对接后的字符串进行sha1加密
	byte[] digest = md.digest(content.toString().getBytes());
	String ciphertext = byteToStr(digest);
	//开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
	return ciphertext != null ? ciphertext.equals(signature.toUpperCase()) : false;
}
 
Example #5
Source File: MessageToken_v2.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Verifies the validity of checksum field
 *
 * @param data the application data
 * @param offset the offset where the data begins
 * @param len the length of the application data
 *
 * @throws GSSException if an error occurs in the checksum calculation
 */
public final boolean verifySign(byte[] data, int offset, int len)
    throws GSSException {

    // debug("\t====In verifySign:====\n");
    // debug("\t\t checksum:   [" + getHexBytes(checksum) + "]\n");
    // debug("\t\t data = [" + getHexBytes(data) + "]\n");

    byte[] myChecksum = getChecksum(data, offset, len);
    // debug("\t\t mychecksum: [" + getHexBytes(myChecksum) +"]\n");

    if (MessageDigest.isEqual(checksum, myChecksum)) {
        // debug("\t\t====Checksum PASS:====\n");
        return true;
    }
    return false;
}
 
Example #6
Source File: SystemTool.java    From KJFrameForAndroid with 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 #7
Source File: CryptoUtils.java    From TelegramApi with MIT License 6 votes vote down vote up
public static String MD5(RandomAccessFile randomAccessFile) {
    try {
        MessageDigest crypt = md5.get();
        crypt.reset();
        byte[] block = new byte[8 * 1024];
        for (int i = 0; i < randomAccessFile.length(); i += 8 * 1024) {
            int len = (int) Math.min(block.length, randomAccessFile.length() - i);
            randomAccessFile.readFully(block, 0, len);
            crypt.update(block, 0, len);
        }
        return ToHex(crypt.digest());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example #8
Source File: ResolverMappingDigest.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<byte[]> computeInternal(@Nonnull FDBRecordContext context,
                                                  @Nullable byte[] continuation,
                                                  @Nonnull MessageDigest messageDigest) {

    return resolver.getMappingSubspaceAsync().thenCompose(mappingSubspace -> {
        final RecordCursor<KeyValue> cursor = KeyValueCursor.Builder.withSubspace(mappingSubspace)
                .setScanProperties(new ScanProperties(ExecuteProperties.newBuilder().setReturnedRowLimit(transactionRowLimit).setIsolationLevel(IsolationLevel.SNAPSHOT).build()))
                .setContext(context)
                .setContinuation(continuation)
                .build();

        return cursor.forEachResult(result -> {
            KeyValue kv = result.get();
            String key = mappingSubspace.unpack(kv.getKey()).getString(0);
            ResolverResult value = resolver.deserializeValue(kv.getValue());

            messageDigest.update(Tuple.from(key, value.getValue(), value.getMetadata()).pack());
        }).thenApply(result -> result.getContinuation().toBytes());
    });
}
 
Example #9
Source File: SignatureFileVerifier.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/** get digest from cache */

    private MessageDigest getDigest(String algorithm) throws SignatureException {
        // check that algorithm is not restricted
        if (!JAR_DISABLED_CHECK.permits(DIGEST_PRIMITIVE_SET, algorithm, null)) {
            SignatureException e =
                    new SignatureException("SignatureFile check failed. " +
                            "Disabled algorithm used: " + algorithm);
            throw e;
        }

        if (createdDigests == null)
            createdDigests = new HashMap<String, MessageDigest>();

        MessageDigest digest = createdDigests.get(algorithm);

        if (digest == null) {
            try {
                digest = MessageDigest.getInstance(algorithm);
                createdDigests.put(algorithm, digest);
            } catch (NoSuchAlgorithmException nsae) {
                // ignore
            }
        }
        return digest;
    }
 
Example #10
Source File: BarometerNetworkActivity.java    From PressureNet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get a unique ID by fetching the phone ID and hashing it
 * 
 * @return
 */
private String getID() {
	try {
		MessageDigest md = MessageDigest.getInstance("MD5");

		String actual_id = Secure.getString(getApplicationContext()
				.getContentResolver(), Secure.ANDROID_ID);
		byte[] bytes = actual_id.getBytes();
		byte[] digest = md.digest(bytes);
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < digest.length; i++) {
			hexString.append(Integer.toHexString(0xFF & digest[i]));
		}
		return hexString.toString();
	} catch (Exception e) {
		return "--";
	}
}
 
Example #11
Source File: MD5Crypt.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * MD5 and Hexify an array of bytes.  Take the input array, MD5 encodes it
 * and then turns it into Hex.
 * @param secretBytes you want md5hexed
 * @return md5hexed String.
 */
public static String md5Hex(byte[] secretBytes) {
    String retval = null;
    // add secret
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
        //byte[] secretBytes = inputString.getBytes("UTF-8");
        md.update(secretBytes);
        // generate the digest
        byte[] digest = md.digest();
        // hexify this puppy
        retval = new String(Hex.encodeHex(digest));
    }
    catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("NoSuchAlgorithm: MD5.  Something" +
                " weird with your JVM, you should be able to do this.", e);
    }
    return retval;
}
 
Example #12
Source File: DigestAuthentication.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private String encode(String src, char[] passwd, MessageDigest md) {
    try {
        md.update(src.getBytes("ISO-8859-1"));
    } catch (java.io.UnsupportedEncodingException uee) {
        assert false;
    }
    if (passwd != null) {
        byte[] passwdBytes = new byte[passwd.length];
        for (int i=0; i<passwd.length; i++)
            passwdBytes[i] = (byte)passwd[i];
        md.update(passwdBytes);
        Arrays.fill(passwdBytes, (byte)0x00);
    }
    byte[] digest = md.digest();

    StringBuffer res = new StringBuffer(digest.length * 2);
    for (int i = 0; i < digest.length; i++) {
        int hashchar = ((digest[i] >>> 4) & 0xf);
        res.append(charArray[hashchar]);
        hashchar = (digest[i] & 0xf);
        res.append(charArray[hashchar]);
    }
    return res.toString();
}
 
Example #13
Source File: XMPPAccountStore.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] encrypt(byte[] data, String key)
    throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        InvalidAlgorithmParameterException {

  Cipher cipher = Cipher.getInstance(TRANSFORMATION);

  MessageDigest digest = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM);
  digest.update(key.getBytes("UTF-8"));

  // default JVM impl. may only support key strength up to 128 bit;
  byte[] keyData = new byte[16];
  System.arraycopy(digest.digest(), 0, keyData, 0, keyData.length);

  SecretKeySpec keySpec = new SecretKeySpec(keyData, SECRET_KEY_ALGORITHM);
  IvParameterSpec ivSpec = new IvParameterSpec(IV);

  data = deflate(data);

  cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

  return xor(cipher.doFinal(data));
}
 
Example #14
Source File: AuthorizeNetSimPaymentGatewayImpl.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
protected String md5sign(final String txId, final String amount) {

        final StringBuilder sign = new StringBuilder();
        sign.append(getParameterValue(AN_MD5_HASH_KEY));
        sign.append(getParameterValue(AN_API_LOGIN_ID));
        sign.append(txId);
        sign.append(amount);
        sign.append("EUR");

        try {
            final Charset charset = StandardCharsets.UTF_8;
            final MessageDigest digest = MessageDigest.getInstance("MD5");
            return new String(Hex.encodeHex(digest.digest(sign.toString().getBytes(charset)))).toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            LOG.error("MD5 not available", e);
            return "MD5 not available";
        }
    }
 
Example #15
Source File: FileUtils.java    From YTPlayer with GNU General Public License v3.0 6 votes vote down vote up
public static String SHA1(InputStream is) {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        for (int read; (read = is.read(buffer)) != -1; ) {
            messageDigest.update(buffer, 0, read);
        }

        Formatter formatter = new Formatter();
        // Convert the byte to hex format
        for (final byte b : messageDigest.digest()) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    } catch (NoSuchAlgorithmException | IOException e) {
        android.util.Log.e(TAG,e.getMessage());
    } finally {
        YTutils.close(is);
    }
    return null;
}
 
Example #16
Source File: DESKey.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof SecretKey))
        return false;

    String thatAlg = ((SecretKey)obj).getAlgorithm();
    if (!(thatAlg.equalsIgnoreCase("DES")))
        return false;

    byte[] thatKey = ((SecretKey)obj).getEncoded();
    boolean ret = MessageDigest.isEqual(this.key, thatKey);
    java.util.Arrays.fill(thatKey, (byte)0x00);
    return ret;
}
 
Example #17
Source File: Md5Util.java    From 12306XposedPlugin with GNU General Public License v3.0 6 votes vote down vote up
public static String encrypt(String string) {
    if (TextUtils.isEmpty(string)) {
        return "";
    }
    MessageDigest md5;
    try {
        md5 = MessageDigest.getInstance("MD5");
        byte[] bytes = md5.digest(string.getBytes());
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            String temp = Integer.toHexString(b & 0xff);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            result.append(temp);
        }
        return result.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example #18
Source File: MD5Utils.java    From YiZhi with Apache License 2.0 6 votes vote down vote up
public static String getMD5(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();
}
 
Example #19
Source File: MessageDigestUtil.java    From netty-restful-server with MIT License 6 votes vote down vote up
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();
        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;
    }
}
 
Example #20
Source File: MD5Util.java    From das with Apache License 2.0 6 votes vote down vote up
public static String parseStrToMd5L32(String str) {
    String reStr = null;
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] bytes = md5.digest(str.getBytes());
        StringBuffer stringBuffer = new StringBuffer();
        for (byte b : bytes) {
            int bt = b & 0xff;
            if (bt < 16) {
                stringBuffer.append(0);
            }
            stringBuffer.append(Integer.toHexString(bt));
        }
        reStr = stringBuffer.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return reStr;
}
 
Example #21
Source File: ChecksumCalculationTask.java    From pgptool with GNU General Public License v3.0 5 votes vote down vote up
public ChecksumCalculationTask(String filePathName, MessageDigest messageDigest,
		ProgressHandler optionalProgressHandler) {
	this.filePathName = filePathName;
	this.messageDigest = messageDigest;
	this.progressHandler = optionalProgressHandler;
	if (progressHandler == null) {
		progressHandler = new ProgressHandlerNoOpImpl();
	}
}
 
Example #22
Source File: MessageDigestHashFunction.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public Hasher newHasher() {
  if (supportsClone) {
    try {
      return new MessageDigestHasher((MessageDigest) prototype.clone(), bytes);
    } catch (CloneNotSupportedException e) {
      // falls through
    }
  }
  return new MessageDigestHasher(getMessageDigest(prototype.getAlgorithm()), bytes);
}
 
Example #23
Source File: BcryptCipherProvider.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, String password, byte[] salt, byte[] iv, int keyLength, boolean encryptMode) throws Exception {
    if (encryptionMethod == null) {
        throw new IllegalArgumentException("The encryption method must be specified");
    }
    if (!encryptionMethod.isCompatibleWithStrongKDFs()) {
        throw new IllegalArgumentException(encryptionMethod.name() + " is not compatible with Bcrypt");
    }

    if (StringUtils.isEmpty(password)) {
        throw new IllegalArgumentException("Encryption with an empty password is not supported");
    }

    String algorithm = encryptionMethod.getAlgorithm();
    String provider = encryptionMethod.getProvider();

    final String cipherName = CipherUtility.parseCipherFromAlgorithm(algorithm);
    if (!CipherUtility.isValidKeyLength(keyLength, cipherName)) {
        throw new IllegalArgumentException(String.valueOf(keyLength) + " is not a valid key length for " + cipherName);
    }

    String bcryptSalt = formatSaltForBcrypt(salt);

    String hash = BCrypt.hashpw(password, bcryptSalt);

    /* The SHA-512 hash is required in order to derive a key longer than 184 bits (the resulting size of the Bcrypt hash) and ensuring the avalanche effect causes higher key entropy (if all
    derived keys follow a consistent pattern, it weakens the strength of the encryption) */
    MessageDigest digest = MessageDigest.getInstance("SHA-512", provider);
    byte[] dk = digest.digest(hash.getBytes(StandardCharsets.UTF_8));
    dk = Arrays.copyOf(dk, keyLength / 8);
    SecretKey tempKey = new SecretKeySpec(dk, algorithm);

    KeyedCipherProvider keyedCipherProvider = new AESKeyedCipherProvider();
    return keyedCipherProvider.getCipher(encryptionMethod, tempKey, iv, encryptMode);
}
 
Example #24
Source File: IIDM2DB.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
public static String computeTopoHash(String topoRep) {

        String base64hash;
        try {
            byte[] digest = MessageDigest.getInstance("SHA-1").digest(topoRep.getBytes("UTF-8"));
            // create a hash from the SHA-1 first 6 bytes
            digest = Arrays.copyOfRange(digest, 0, 6);
            base64hash = Base64.encodeBase64String(digest).trim();
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
            throw new RuntimeException("Failed to compute topology hash from" + topoRep, e);
        }

        return base64hash;
    }
 
Example #25
Source File: SignUtils.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 5 votes vote down vote up
public static byte[] calculateHASH(String digestOID, byte[] data) throws Exception{
    String digestName = "";
    
    try{
        if(Security.getProvider("BC") == null)
            Security.addProvider(new BouncyCastleProvider());
        
        if(digestOID.equals(CMSSignedDataGenerator.DIGEST_MD5))
            digestName = "MD5";
        if(digestOID.equals(CMSSignedDataGenerator.DIGEST_SHA1))
            digestName = "SHA-1";
        if(digestOID.equals(CMSSignedDataGenerator.DIGEST_SHA256))
            digestName = "SHA-256";
        if(digestOID.equals(CMSSignedDataGenerator.DIGEST_SHA384))
            digestName = "SHA-384";
        if(digestOID.equals(CMSSignedDataGenerator.DIGEST_SHA512))
            digestName = "SHA-512";
        
        if(digestName.equals(""))
            throw new Exception("Unsupported digestOID");
        
        MessageDigest md = MessageDigest.getInstance(digestName, "BC");
        md.update(data);
        
        byte[] hash = md.digest();

        return hash;
    }catch(Exception e){
        throw new Exception("Error on the generation for the Hash "+digestName+":\n"+e.getMessage());
    }
}
 
Example #26
Source File: Encryption.java    From spring-boot-demo-all with Apache License 2.0 5 votes vote down vote up
public static String sha1(String str) {
    if (str == null) {
        return null;
    }
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        messageDigest.update(str.getBytes("UTF-8"));
        return getFormattedText(messageDigest.digest());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example #27
Source File: WebSocketClient.java    From hack.chat-android with MIT License 5 votes vote down vote up
private String createSecretValidation(String secret) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update((secret + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes());
        return Base64.encodeToString(md.digest(), Base64.DEFAULT).trim();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
 
Example #28
Source File: VolumeLayout.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
@Override
  protected int getMKKDFNumIterations(MessageDigest hashFunc)
  {
return _numIterations > 0 ?
		getKDFIterationsFromPIM(_numIterations) :
		"ripemd160".equalsIgnoreCase(hashFunc.getAlgorithm()) ?
				655331 :
				500000;
  }
 
Example #29
Source File: ProcessSensitiveDataUtils.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Conversion to md5 hash string.
 *
 * @param val String value.
 * @return MD5 hash string.
 * */
public static String md5(String val) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(val.getBytes(UTF_8));

        byte[] digest = md.digest();

        return Base64.getEncoder().encodeToString(digest);
    }
    catch (Exception e) {
        throw new IgniteException(e);
    }
}
 
Example #30
Source File: Main.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/** Display the location and checksum of a class. */
void showClass(String className) {
    PrintWriter pw = log.getWriter(WriterKind.NOTICE);
    pw.println("javac: show class: " + className);
    URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
    if (url == null)
        pw.println("  class not found");
    else {
        pw.println("  " + url);
        try {
            final String algorithm = "MD5";
            byte[] digest;
            MessageDigest md = MessageDigest.getInstance(algorithm);
            DigestInputStream in = new DigestInputStream(url.openStream(), md);
            try {
                byte[] buf = new byte[8192];
                int n;
                do { n = in.read(buf); } while (n > 0);
                digest = md.digest();
            } finally {
                in.close();
            }
            StringBuilder sb = new StringBuilder();
            for (byte b: digest)
                sb.append(String.format("%02x", b));
            pw.println("  " + algorithm + " checksum: " + sb);
        } catch (Exception e) {
            pw.println("  cannot compute digest: " + e);
        }
    }
}