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: MD5Util.java From das with Apache License 2.0 | 6 votes |
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
Source File: SystemTool.java From KJFrameForAndroid with Apache License 2.0 | 6 votes |
/** * 将签名字符串转换成需要的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
Source File: ShardStrategyFactory.java From moleculer-java with MIT License | 6 votes |
@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: Crypt.java From projectforge-webapp with GNU General Public License v3.0 | 6 votes |
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
Source File: CryptoUtils.java From TelegramApi with MIT License | 6 votes |
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
Source File: ResolverMappingDigest.java From fdb-record-layer with Apache License 2.0 | 6 votes |
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
Source File: BarometerNetworkActivity.java From PressureNet with GNU General Public License v3.0 | 6 votes |
/** * 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
Source File: MessageDigestUtil.java From netty-restful-server with MIT License | 6 votes |
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
Source File: MD5Crypt.java From uyuni with GNU General Public License v2.0 | 6 votes |
/** * 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
Source File: DigestAuthentication.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
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
Source File: FileUtils.java From YTPlayer with GNU General Public License v3.0 | 6 votes |
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
Source File: DESKey.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
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
Source File: Md5Util.java From 12306XposedPlugin with GNU General Public License v3.0 | 6 votes |
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
Source File: RangerKeyStore.java From ranger with Apache License 2.0 | 6 votes |
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
Source File: MD5Utils.java From YiZhi with Apache License 2.0 | 6 votes |
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
Source File: AuthorizeNetSimPaymentGatewayImpl.java From yes-cart with Apache License 2.0 | 6 votes |
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
Source File: XMPPAccountStore.java From saros with GNU General Public License v2.0 | 6 votes |
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
Source File: SignatureFileVerifier.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** 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
Source File: CoreControllerHelp.java From JavaWeb with Apache License 2.0 | 6 votes |
/** 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
Source File: MessageToken_v2.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
/** * 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
Source File: BoxFileTest.java From box-java-sdk with Apache License 2.0 | 5 votes |
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
Source File: CubeDesc.java From Kylin with Apache License 2.0 | 5 votes |
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
Source File: SignatureValidator.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
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
Source File: HadoopFsValidator.java From hadoop-ozone with Apache License 2.0 | 5 votes |
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
Source File: PathHashUtil.java From sakai with Educational Community License v2.0 | 5 votes |
/** * 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
Source File: CheckSumBuilder.java From classchecks with Apache License 2.0 | 5 votes |
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
Source File: Utility.java From kognitivo with Apache License 2.0 | 5 votes |
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
Source File: AccountDAO.java From ezScrum with GNU General Public License v2.0 | 5 votes |
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
Source File: MessageDigestUtils.java From softservice with MIT License | 5 votes |
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
Source File: ManifestDigester.java From Bytecoder with Apache License 2.0 | 5 votes |
/** 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(); }