Java Code Examples for java.security.MessageDigest

The following examples show how to use java.security.MessageDigest. These examples are extracted from open source projects.
Example 1
Project: das   File: MD5Util.java    License: 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 2
Project: KJFrameForAndroid   File: SystemTool.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 3
Project: moleculer-java   File: ShardStrategyFactory.java    License: 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
Project: projectforge-webapp   File: Crypt.java    License: 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 5
Project: TelegramApi   File: CryptoUtils.java    License: 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 6
Project: fdb-record-layer   File: ResolverMappingDigest.java    License: 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 7
Project: PressureNet   File: BarometerNetworkActivity.java    License: 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 8
Project: netty-restful-server   File: MessageDigestUtil.java    License: 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 9
Project: uyuni   File: MD5Crypt.java    License: 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 10
Project: openjdk-jdk8u-backup   File: DigestAuthentication.java    License: 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 11
Project: YTPlayer   File: FileUtils.java    License: 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 12
Project: openjdk-jdk8u-backup   File: DESKey.java    License: 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 13
Project: 12306XposedPlugin   File: Md5Util.java    License: 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 14
Project: ranger   File: RangerKeyStore.java    License: 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 15
Project: YiZhi   File: MD5Utils.java    License: 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 16
Project: yes-cart   File: AuthorizeNetSimPaymentGatewayImpl.java    License: 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 17
Project: saros   File: XMPPAccountStore.java    License: 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 18
Project: jdk8u-jdk   File: SignatureFileVerifier.java    License: 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 19
Project: JavaWeb   File: CoreControllerHelp.java    License: 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 20
Project: openjdk-8   File: MessageToken_v2.java    License: 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 21
Project: box-java-sdk   File: BoxFileTest.java    License: Apache License 2.0 5 votes vote down vote up
private MessageDigest uploadParts(BoxFile uploadedFile, BoxFileUploadSession.Info session,
                                  long fileSize, String fileName) throws Exception {

    URL fileURL = this.getClass().getResource("/sample-files/" + fileName);
    String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8");
    File file = new File(filePath);

    FileInputStream stream = new FileInputStream(file);
    MessageDigest fileDigest = MessageDigest.getInstance("SHA1");
    DigestInputStream dis = new DigestInputStream(stream, fileDigest);

    long offset = 0;
    byte[] bytes = null;
    long processed = 0;
    boolean canBreak = false;
    while (true) {
        long min = session.getPartSize();
        long diff = fileSize - processed;
        if (diff < min) {
            min = diff;
            canBreak = true;
        }

        BoxFileUploadSessionPart part = session.getResource().uploadPart(dis, offset, (int) min, fileSize);
        Assert.assertNotNull(part.getSha1());
        Assert.assertNotNull(part.getPartId());
        Assert.assertEquals(part.getOffset(), offset);
        Assert.assertTrue(part.getSize() <= session.getPartSize());
        offset = offset + session.getPartSize();
        processed += min;
        if (canBreak) {
            break;
        }
    }

    return fileDigest;
}
 
Example 22
Project: Kylin   File: CubeDesc.java    License: Apache License 2.0 5 votes vote down vote up
public String calculateSignature() {
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");
        StringBuilder sigString = new StringBuilder();
        sigString.append(this.name).append("|").append(this.getFactTable()).append("|").append(JsonUtil.writeValueAsString(this.model.getPartitionDesc())).append("|").append(JsonUtil.writeValueAsString(this.dimensions)).append("|").append(JsonUtil.writeValueAsString(this.measures)).append("|").append(JsonUtil.writeValueAsString(this.rowkey)).append("|").append(JsonUtil.writeValueAsString(this.hbaseMapping));

        byte[] signature = md.digest(sigString.toString().getBytes());
        return new String(Base64.encodeBase64(signature));
    } catch (NoSuchAlgorithmException | JsonProcessingException e) {
        throw new RuntimeException("Failed to calculate signature");
    }
}
 
Example 23
Project: openjdk-jdk9   File: SignatureValidator.java    License: GNU General Public License v2.0 5 votes vote down vote up
private boolean digestInputEqual(Reference ref) throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA1");
    InputStream is = ref.getDigestInputStream();
    int nbytes;
    byte[] buf = new byte[256];
    while ((nbytes = is.read(buf, 0, buf.length)) != -1) {
        md.update(buf, 0, nbytes);
    }
    return Arrays.equals(md.digest(), ref.getDigestValue());
}
 
Example 24
Project: hadoop-ozone   File: HadoopFsValidator.java    License: Apache License 2.0 5 votes vote down vote up
private void validateFile(long counter) throws Exception {
  Path file = new Path(rootPath + "/" + generateObjectName(counter));

  byte[] content = timer.time(() -> {
    try (FSDataInputStream input = fileSystem.open(file)) {
      return IOUtils.toByteArray(input);
    }
  });

  if (!MessageDigest.isEqual(referenceDigest, getDigest(content))) {
    throw new IllegalStateException(
        "Reference (=first) message digest doesn't match with digest of "
            + file.toString());
  }
}
 
Example 25
Project: sakai   File: PathHashUtil.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * create a SHA1 hash of the path
 *
 * @param nodePath
 * @param encode
 * @return some SHA1 hash value possibly
 * @throws NoSuchAlgorithmException
 */
public static String hash(String nodePath)
{
	MessageDigest mdigest  = (MessageDigest) digest.get();
	if ( mdigest == null ) 
	{
		try
		{
			mdigest = MessageDigest.getInstance("SHA1");
            digest.set(mdigest);
		}
		catch (NoSuchAlgorithmException e)
		{
		    throw new RuntimeException("Failed to find SHA1 message digest: " + e, e);
		}
	}
	byte[] b = mdigest.digest(nodePath.getBytes());
	char[] c = new char[b.length * 2];
	for (int i = 0; i < b.length; i++)
	{
		c[i * 2] = encode[b[i]&0x0f];
		c[i * 2 + 1] = encode[(b[i]>>4)&0x0f];
	}
	String encoded =  new String(c);
	log.debug("Encoded "+nodePath+" as "+encoded);
	return encoded;
}
 
Example 26
Project: classchecks   File: CheckSumBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static String encode(String algorithm, String value) {
    if (value == null) {
        return null;
    }
    try {
        MessageDigest messageDigest
                = MessageDigest.getInstance(algorithm);
        messageDigest.update(value.getBytes());
        return getFormattedText(messageDigest.digest());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 27
Project: kognitivo   File: Utility.java    License: Apache License 2.0 5 votes vote down vote up
private static String hashBytes(MessageDigest hash, byte[] bytes) {
    hash.update(bytes);
    byte[] digest = hash.digest();
    StringBuilder builder = new StringBuilder();
    for (int b : digest) {
        builder.append(Integer.toHexString((b >> 4) & 0xf));
        builder.append(Integer.toHexString((b >> 0) & 0xf));
    }
    return builder.toString();
}
 
Example 28
Project: ezScrum   File: AccountDAO.java    License: GNU General Public License v2.0 5 votes vote down vote up
public String getMd5(String str) {
	MessageDigest md = null;
	try {
		md = MessageDigest.getInstance("MD5");
	} catch (Exception e) {
		e.printStackTrace();
	}
	md.update(str.getBytes());
	byte b[] = md.digest();
	str = byte2hex(b);
	return str;
}
 
Example 29
Project: softservice   File: MessageDigestUtils.java    License: MIT License 5 votes vote down vote up
public static String encrypt(String password,String algorithm){
	try {
		MessageDigest md = MessageDigest.getInstance(algorithm);
		byte[] b = md.digest(password.getBytes());
		return ByteUtils.byte2HexString(b);
	}catch (Exception e){
		e.printStackTrace();
		return null;
	}
}
 
Example 30
Project: Bytecoder   File: ManifestDigester.java    License: Apache License 2.0 5 votes vote down vote up
/** Netscape doesn't include the new line. Intel and JavaSoft do */

        public byte[] digestWorkaround(MessageDigest md)
        {
            md.reset();
            for (Section sec : sections) {
                md.update(sec.rawBytes, sec.offset, sec.length);
            }
            return md.digest();
        }
 
Example 31
Project: md_blockchain   File: MerkleHash.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Compute SHA256 hash of a byte array.
 *
 * @param buffer of bytes
 */
private void computeHash(byte[] buffer) {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        this.value = digest.digest(buffer);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}
 
Example 32
Project: jdk8u-jdk   File: PKCS12KeyStore.java    License: GNU General Public License v2.0 5 votes vote down vote up
private byte[] generateHash(byte[] data) throws IOException
{
    byte[] digest = null;

    try {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.update(data);
        digest = md.digest();
    } catch (Exception e) {
        throw new IOException("generateHash failed: " + e, e);
    }
    return digest;
}
 
Example 33
Project: helidon-build-tools   File: PreprocessAsciiDocMojo.java    License: Apache License 2.0 5 votes vote down vote up
private byte[] digest(Path path) throws IOException, NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("MD5");

    byte[] buffer = new byte[256];
    try (InputStream is = new BufferedInputStream(Files.newInputStream(path));
         DigestInputStream dis = new DigestInputStream(is, md)) {
        while (dis.read(buffer) != -1) {
        }
    }
    return md.digest();
}
 
Example 34
Project: itext2   File: PdfPKCS7.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Checks if the timestamp refers to this document.
 * @throws java.security.NoSuchAlgorithmException on error
 * @return true if it checks false otherwise
 * @since	2.1.6
 */
public boolean verifyTimestampImprint() throws NoSuchAlgorithmException {
    if (timeStampToken == null)
        return false;
    MessageImprint imprint = timeStampToken.getTimeStampInfo().toASN1Structure().getMessageImprint();
    TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
    String algOID = info.getMessageImprintAlgOID().getId();
    byte[] md =  MessageDigest.getInstance(getStandardJavaName(getDigest(algOID))).digest(digest);
    byte[] imphashed = imprint.getHashedMessage();
    boolean res = Arrays.equals(md, imphashed);
    return res;
}
 
Example 35
Project: Bytecoder   File: TSRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a timestamp request for the supplied data.
 *
 * @param toBeTimeStamped  The data to be timestamped.
 * @param messageDigest The MessageDigest of the hash algorithm to use.
 * @throws NoSuchAlgorithmException if the hash algorithm is not supported
 */
public TSRequest(String tSAPolicyID, byte[] toBeTimeStamped, MessageDigest messageDigest)
    throws NoSuchAlgorithmException {

    this.policyId = tSAPolicyID;
    this.hashAlgorithmId = AlgorithmId.get(messageDigest.getAlgorithm());
    this.hashValue = messageDigest.digest(toBeTimeStamped);
}
 
Example 36
Project: codebuff   File: MessageDigestHashFunction.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static boolean supportsClone(MessageDigest digest) {
  try {
    digest.clone();
    return true;
  } catch (CloneNotSupportedException e) {
    return false;
  }
}
 
Example 37
Project: hack.chat-android   File: WebSocketClient.java    License: 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 38
Project: Websocket-Smart-Card-Signer   File: SignUtils.java    License: 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 39
Project: localization_nifi   File: BcryptCipherProvider.java    License: 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 40
Project: rabbitmq-operator   File: TestRabbitMQPasswordConverter.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
private void setup() throws NoSuchAlgorithmException {
    final Random myRandom = new Random() {
        @Override
        public int nextInt() {
            return SALT;
        }
    };

    converter = new RabbitMQPasswordConverter(myRandom, MessageDigest.getInstance("SHA-256"), Base64.getEncoder(), Base64.getDecoder());
}