Java Code Examples for java.security.MessageDigest#update()
The following examples show how to use
java.security.MessageDigest#update() .
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: MD5Authentication.java From vertx-sql-client with Apache License 2.0 | 6 votes |
public static String encode(String username, String password, byte[] salt) { byte[] digest, passDigest; MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } messageDigest.update(password.getBytes(UTF_8)); messageDigest.update(username.getBytes(UTF_8)); digest = messageDigest.digest(); byte[] hexDigest = toHex(digest).getBytes(US_ASCII); messageDigest.update(hexDigest); messageDigest.update(salt); passDigest = messageDigest.digest(); return "md5" + toHex(passDigest); }
Example 2
Source File: TextUtils.java From netbeans with Apache License 2.0 | 6 votes |
public static String getMD5(String name) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); // NOI18N } catch (NoSuchAlgorithmException e) { // should not happen return null; } digest.update(name.getBytes()); byte[] hash = digest.digest(); StringBuilder ret = new StringBuilder(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(hash[i] & 0x000000FF); if(hex.length()==1) { hex = "0" + hex; // NOI18N } ret.append(hex); } return ret.toString(); }
Example 3
Source File: FileUtil.java From AppUpdate with Apache License 2.0 | 6 votes |
/** * 获取一个文件的MD5 * * @param file 文件 * @return MD5 */ public static String getFileMD5(File file) { try { byte[] buffer = new byte[1024]; int len; MessageDigest digest = MessageDigest.getInstance("MD5"); FileInputStream in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { digest.update(buffer, 0, len); } in.close(); BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16).toUpperCase(); } catch (Exception e) { e.printStackTrace(); return ""; } }
Example 4
Source File: AppUtil.java From AndroidStudyDemo with GNU General Public License v2.0 | 6 votes |
static public String getApkMD5(Context context) { String apkMD5 = ""; Signature signature = getApkSignature(context); if (signature == null) return apkMD5; MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { Logger.e(e); } messageDigest.update(signature.toByteArray()); byte[] digest = messageDigest.digest(); apkMD5 = toHexString(digest); Logger.e("Apk MD5 : "+apkMD5); return apkMD5; }
Example 5
Source File: CheckCertId.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
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 6
Source File: BlobServerConnection.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
/** * Reads a full file from <tt>inputStream</tt> into <tt>incomingFile</tt> returning its checksum. * * @param inputStream * stream to read from * @param incomingFile * file to write to * @param buf * An auxiliary buffer for data serialization/deserialization * * @return the received file's content hash * * @throws IOException * thrown if an I/O error occurs while reading/writing data from/to the respective streams */ private static byte[] readFileFully( final InputStream inputStream, final File incomingFile, final byte[] buf) throws IOException { MessageDigest md = BlobUtils.createMessageDigest(); try (FileOutputStream fos = new FileOutputStream(incomingFile)) { while (true) { final int bytesExpected = readLength(inputStream); if (bytesExpected == -1) { // done break; } if (bytesExpected > BUFFER_SIZE) { throw new IOException( "Unexpected number of incoming bytes: " + bytesExpected); } readFully(inputStream, buf, 0, bytesExpected, "buffer"); fos.write(buf, 0, bytesExpected); md.update(buf, 0, bytesExpected); } return md.digest(); } }
Example 7
Source File: MD5Utils.java From HA-DB with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * 32位加密 * * @param sourceStr * @return */ public static String MD5(String sourceStr) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(sourceStr.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); } catch (NoSuchAlgorithmException e) { System.out.println(e); } return result; }
Example 8
Source File: DexWriter.java From ZjDroid with Apache License 2.0 | 6 votes |
private void updateSignature(@Nonnull DexDataStore dataStore) throws IOException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } byte[] buffer = new byte[4 * 1024]; InputStream input = dataStore.readAt(HeaderItem.SIGNATURE_DATA_START_OFFSET); int bytesRead = input.read(buffer); while (bytesRead >= 0) { md.update(buffer, 0, bytesRead); bytesRead = input.read(buffer); } byte[] signature = md.digest(); if (signature.length != HeaderItem.SIGNATURE_SIZE) { throw new RuntimeException("unexpected digest write: " + signature.length + " bytes"); } // write signature OutputStream output = dataStore.outputAt(HeaderItem.SIGNATURE_OFFSET); output.write(signature); output.close(); }
Example 9
Source File: MTProto.java From TelegramApi with MIT License | 6 votes |
private byte[] optimizedSHA(byte[] serverSalt, byte[] session, long msgId, int seq, int len, byte[] data, int datalen) { try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(serverSalt); crypt.update(session); crypt.update(longToBytes(msgId)); crypt.update(intToBytes(seq)); crypt.update(intToBytes(len)); crypt.update(data, 0, datalen); return crypt.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
Example 10
Source File: PKCS12KeyStore.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
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 11
Source File: CertId.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public CertId(X500Principal issuerName, PublicKey issuerKey, SerialNumber serialNumber) throws IOException { // compute issuerNameHash MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException nsae) { throw new IOException("Unable to create CertId", nsae); } hashAlgId = SHA1_ALGID; md.update(issuerName.getEncoded()); issuerNameHash = md.digest(); // compute issuerKeyHash (remove the tag and length) byte[] pubKey = issuerKey.getEncoded(); DerValue val = new DerValue(pubKey); DerValue[] seq = new DerValue[2]; seq[0] = val.data.getDerValue(); // AlgorithmID seq[1] = val.data.getDerValue(); // Key byte[] keyBytes = seq[1].getBitString(); md.update(keyBytes); issuerKeyHash = md.digest(); certSerialNumber = serialNumber; if (debug) { HexDumpEncoder encoder = new HexDumpEncoder(); System.out.println("Issuer Name is " + issuerName); System.out.println("issuerNameHash is " + encoder.encodeBuffer(issuerNameHash)); System.out.println("issuerKeyHash is " + encoder.encodeBuffer(issuerKeyHash)); System.out.println("SerialNumber is " + serialNumber.getNumber()); } }
Example 12
Source File: UserService.java From tutorials with MIT License | 5 votes |
private String digestSHA(final String password) { String base64; try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(password.getBytes()); base64 = Base64.getEncoder() .encodeToString(digest.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return "{SHA}" + base64; }
Example 13
Source File: AccountDAOTest.java From ezScrum with GNU General Public License v2.0 | 5 votes |
private 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 14
Source File: SessionManage.java From ans-android-sdk with GNU General Public License v3.0 | 5 votes |
/** * MD5加密 */ private String getMD5(String val) { byte[] m = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(val.getBytes()); m = md5.digest(); } catch (Throwable ignore) { ExceptionUtil.exceptionThrow(ignore); } return getString(m); }
Example 15
Source File: Source.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
private byte[] getDigestBytes() { byte[] ldigest = digest; if (ldigest == null) { final char[] content = data(); final byte[] bytes = new byte[content.length * 2]; for (int i = 0; i < content.length; i++) { bytes[i * 2] = (byte) (content[i] & 0x00ff); bytes[i * 2 + 1] = (byte) ((content[i] & 0xff00) >> 8); } try { final MessageDigest md = MessageDigest.getInstance("SHA-1"); if (name != null) { md.update(name.getBytes(StandardCharsets.UTF_8)); } if (base != null) { md.update(base.getBytes(StandardCharsets.UTF_8)); } if (getURL() != null) { md.update(getURL().toString().getBytes(StandardCharsets.UTF_8)); } digest = ldigest = BASE64.encode(md.digest(bytes)); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException(e); } } return ldigest; }
Example 16
Source File: ItemHashUtil.java From sakai with Educational Community License v2.0 | 4 votes |
String hashResource(ContentResource cr, long lengthInKBToHash) throws NoSuchAlgorithmException, IOException, ServerOverloadException { if ( cr == null ) { return null; } final String algorithm = "SHA-256"; // compute the digest using the MD5 algorithm final MessageDigest md = MessageDigest.getInstance(algorithm); //To improve performance, we will only hash some bytes of the file. if (lengthInKBToHash<=0L){ lengthInKBToHash = Long.MAX_VALUE; } final InputStream fis = cr.streamContent(); try { final byte[] buffer = new byte[1024]; int numRead; long lengthToRead = 0; do { numRead = fis.read(buffer); if (numRead > 0) { md.update(buffer, 0, numRead); lengthToRead += 1; } } while ((numRead != -1) && (lengthToRead < lengthInKBToHash)); } finally { if ( fis != null ) { try { fis.close(); } catch ( Exception e ) { //nothing to do } } } // Include the file length as a disambiguator for files which otherwise happen to contain the same bytes in the // lengthInKBToHash range. We don't include the file name in the hash base because this might be a renamed copy // of a file, in which case the name is a spurious disambiguator for our purposes. md.update((""+cr.getContentLength()).getBytes("UTF-8")); byte[] digest = md.digest(); return Base64.encodeBase64String(digest); }
Example 17
Source File: KeyProtector.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
private byte[] recover(byte[] protectedKey) throws UnrecoverableKeyException, NoSuchAlgorithmException { int i, j; byte[] digest; int numRounds; int xorOffset; // offset in xorKey where next digest will be stored int encrKeyLen; // the length of the encrpyted key MessageDigest md = MessageDigest.getInstance("SHA"); // Get the salt associated with this key (the first SALT_LEN bytes of // <code>protectedKey</code>) byte[] salt = new byte[SALT_LEN]; System.arraycopy(protectedKey, 0, salt, 0, SALT_LEN); // Determine the number of digest rounds encrKeyLen = protectedKey.length - SALT_LEN - DIGEST_LEN; numRounds = encrKeyLen / DIGEST_LEN; if ((encrKeyLen % DIGEST_LEN) != 0) numRounds++; // Get the encrypted key portion and store it in "encrKey" byte[] encrKey = new byte[encrKeyLen]; System.arraycopy(protectedKey, SALT_LEN, encrKey, 0, encrKeyLen); // Set up the byte array which will be XORed with "encrKey" byte[] xorKey = new byte[encrKey.length]; // Convert password to byte array, so that it can be digested byte[] passwdBytes = new byte[password.length * 2]; for (i=0, j=0; i<password.length; i++) { passwdBytes[j++] = (byte)(password[i] >> 8); passwdBytes[j++] = (byte)password[i]; } // Compute the digests, and store them in "xorKey" for (i = 0, xorOffset = 0, digest = salt; i < numRounds; i++, xorOffset += DIGEST_LEN) { md.update(passwdBytes); md.update(digest); digest = md.digest(); md.reset(); // Copy the digest into "xorKey" if (i < numRounds - 1) { System.arraycopy(digest, 0, xorKey, xorOffset, digest.length); } else { System.arraycopy(digest, 0, xorKey, xorOffset, xorKey.length - xorOffset); } } // XOR "encrKey" with "xorKey", and store the result in "plainKey" byte[] plainKey = new byte[encrKey.length]; for (i = 0; i < plainKey.length; i++) { plainKey[i] = (byte)(encrKey[i] ^ xorKey[i]); } // Check the integrity of the recovered key by concatenating it with // the password, digesting the concatenation, and comparing the // result of the digest operation with the digest provided at the end // of <code>protectedKey</code>. If the two digest values are // different, throw an exception. md.update(passwdBytes); java.util.Arrays.fill(passwdBytes, (byte)0x00); passwdBytes = null; md.update(plainKey); digest = md.digest(); md.reset(); for (i = 0; i < digest.length; i++) { if (digest[i] != protectedKey[SALT_LEN + encrKeyLen + i]) { throw new UnrecoverableKeyException("Cannot recover key"); } } return plainKey; }
Example 18
Source File: ZipSigner.java From fdroidclient with GNU General Public License v3.0 | 4 votes |
protected String autoDetectKey(String mode, Map<String, ZioEntry> zioEntries) throws NoSuchAlgorithmException, IOException { boolean debug = getLogger().isDebugEnabled(); if (!mode.startsWith(MODE_AUTO)) return mode; // Auto-determine which keys to use String keyName = null; // Start by finding the signature block file in the input. for (Map.Entry<String, ZioEntry> entry : zioEntries.entrySet()) { String entryName = entry.getKey(); if (entryName.startsWith("META-INF/") && entryName.endsWith(".RSA")) { // Compute MD5 of the first 1458 bytes, which is the size of our signature block templates -- // e.g., the portion of the sig block file that is the same for a given certificate. MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] entryData = entry.getValue().getData(); if (entryData.length < 1458) break; // sig block too short to be a supported key md5.update(entryData, 0, 1458); byte[] rawDigest = md5.digest(); // Create the hex representation of the digest value StringBuilder builder = new StringBuilder(); for (byte b : rawDigest) { builder.append(String.format("%02x", b)); } String md5String = builder.toString(); // Lookup the key name keyName = autoKeyDetect.get(md5String); if (debug) { if (keyName != null) { getLogger().debug(String.format("Auto-determined key=%s using md5=%s", keyName, md5String)); } else { getLogger().debug(String.format("Auto key determination failed for md5=%s", md5String)); } } if (keyName != null) return keyName; } } if (mode.equals(MODE_AUTO_TESTKEY)) { // in auto-testkey mode, fallback to the testkey if it couldn't be determined if (debug) getLogger().debug("Falling back to key=" + keyName); return KEY_TESTKEY; } else if (mode.equals(MODE_AUTO_NONE)) { // in auto-node mode, simply copy the input to the output when the key can't be determined. if (debug) getLogger().debug("Unable to determine key, returning: " + KEY_NONE); return KEY_NONE; } return null; }
Example 19
Source File: HALogFile.java From database with GNU General Public License v2.0 | 4 votes |
static void computeDigest(final IReopenChannel<FileChannel> reopener, final MessageDigest digest) throws DigestException, IOException { IBufferAccess buf = null; try { try { // Acquire a buffer. buf = DirectBufferPool.INSTANCE.acquire(); } catch (InterruptedException ex) { // Wrap and re-throw. throw new IOException(ex); } // The backing ByteBuffer. final ByteBuffer b = buf.buffer(); // // A byte[] with the same capacity as that ByteBuffer. // final byte[] a = new byte[b.capacity()]; // The capacity of that buffer (typically 1MB). final int bufferCapacity = b.capacity(); // The size of the file at the moment we begin. final long fileExtent = reopener.reopenChannel().size(); // The #of bytes whose digest will be computed. final long totalBytes = fileExtent; // The #of bytes remaining. long remaining = totalBytes; // The offset. long offset = 0L; // The block sequence. long sequence = 0L; if (log.isInfoEnabled()) log.info("Computing digest: nbytes=" + totalBytes); while (remaining > 0) { final int nbytes = (int) Math.min((long) bufferCapacity, remaining); if (log.isDebugEnabled()) log.debug("Computing digest: sequence=" + sequence + ", offset=" + offset + ", nbytes=" + nbytes); // Setup for read. b.position(0); b.limit(nbytes); // read block FileChannelUtility.readAll(reopener, b, offset); // // Copy data into our byte[]. // final byte[] c = BytesUtil.toArray(b, false/* forceCopy */, a); // update digest // digest.update(c, 0/* off */, nbytes/* len */); digest.update(b); offset += nbytes; remaining -= nbytes; sequence++; } if (log.isInfoEnabled()) log.info("Computed digest: #blocks=" + sequence + ", #bytes=" + totalBytes); // Done. return; } finally { if (buf != null) { try { // Release the direct buffer. buf.release(); } catch (InterruptedException e) { log.warn(e); } } } }
Example 20
Source File: Sha256.java From EosCommander with MIT License | 4 votes |
public static Sha256 from(byte[] data, int offset, int length) { MessageDigest digest; digest = getSha256Digest(); digest.update(data, offset, length); return new Sha256(digest.digest()); }