Java Code Examples for java.security.MessageDigest.reset()

The following are Jave code examples for showing how to use reset() of the java.security.MessageDigest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: BibliotecaPS   File: Security.java   View Source Code Vote up 6 votes
public static byte[] scramble411(String password, String seed, String passwordEncoding) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest md = MessageDigest.getInstance("SHA-1");

    byte[] passwordHashStage1 = md.digest((passwordEncoding == null || passwordEncoding.length() == 0) ? StringUtils.getBytes(password)
            : StringUtils.getBytes(password, passwordEncoding));
    md.reset();

    byte[] passwordHashStage2 = md.digest(passwordHashStage1);
    md.reset();

    byte[] seedAsBytes = StringUtils.getBytes(seed, "ASCII"); // for debugging
    md.update(seedAsBytes);
    md.update(passwordHashStage2);

    byte[] toBeXord = md.digest();

    int numToXor = toBeXord.length;

    for (int i = 0; i < numToXor; i++) {
        toBeXord[i] = (byte) (toBeXord[i] ^ passwordHashStage1[i]);
    }

    return toBeXord;
}
 
Example 2
Project: javaide   File: CrashConstants.java   View Source Code Vote up 6 votes
/**
 * Get a SHA-256 hash of the input string if the algorithm is available. If the algorithm is
 * unavailable, return empty string.
 *
 * @param input the string to hash.
 * @return a SHA-256 hash of the input or the input if SHA-256 is not available (should not happen).
 */
private static String tryHashStringSha256(Context context, String input) {
    String salt = createSalt(context);
    try {
        // Get a Sha256 digest
        MessageDigest hash = MessageDigest.getInstance("SHA-256");
        hash.reset();
        hash.update(input.getBytes());
        hash.update(salt.getBytes());
        byte[] hashedBytes = hash.digest();

        return bytesToHex(hashedBytes);
    } catch (NoSuchAlgorithmException e) {
        // All android devices should support SHA256, but if unavailable return input
        return input;
    }
}
 
Example 3
Project: hadoop   File: RandomSeedGenerator.java   View Source Code Vote up 6 votes
/**
 * Generates a new random seed.
 *
 * @param streamId a string identifying the stream of random numbers
 * @param masterSeed higher level master random seed
 * @return the random seed. Different (streamId, masterSeed) pairs result in
 *         (vastly) different random seeds.
 */   
public static long getSeed(String streamId, long masterSeed) {
  MessageDigest md5 = md5Holder.get();
  md5.reset();
  //'/' : make sure that we don't get the same str from ('11',0) and ('1',10)
  // We could have fed the bytes of masterSeed one by one to md5.update()
  // instead
  String str = streamId + '/' + masterSeed;
  byte[] digest = md5.digest(str.getBytes(UTF_8));
  // Create a long from the first 8 bytes of the digest
  // This is fine as MD5 has the avalanche property.
  // Paranoids could have XOR folded the other 8 bytes in too. 
  long seed = 0;
  for (int i=0; i<8; i++) {
    seed = (seed<<8) + ((int)digest[i]+128);
  }
  return seed;
}
 
Example 4
Project: AlipayOrdersSupervisor-GUI   File: Order.java   View Source Code Vote up 6 votes
public static String Sign(ApsvOrder order, String secret) {
    String[] data = new String[]{order.time, order.tradeNo, Float.toString(order.amount), order.status, secret};
    String dataStr = String.join("|", data);
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.reset();
        md5.update(dataStr.getBytes(Charset.forName("UTF-8")));
        byte[] dataBytes = md5.digest();
        StringBuffer buffer = new StringBuffer();
        for (int i=0; i<dataBytes.length; i++) {
            if (Integer.toHexString(0xFF & dataBytes[i]).length() == 1)
                buffer.append("0").append(
                        Integer.toHexString(0xFF & dataBytes[i]));
            else
                buffer.append(Integer.toHexString(0xFF & dataBytes[i]));
        }
        return buffer.toString();
    } catch (NoSuchAlgorithmException e) {
        return "";
    }
}
 
Example 5
Project: JRediClients   File: RedissonSortedSet.java   View Source Code Vote up 6 votes
private static String calcClassSign(String name) {
    try {
        Class<?> clazz = Class.forName(name);

        ByteArrayOutputStream result = new ByteArrayOutputStream();
        ObjectOutputStream outputStream = new ObjectOutputStream(result);
        outputStream.writeObject(clazz);
        outputStream.close();

        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(result.toByteArray());

        return new BigInteger(1, crypt.digest()).toString(16);
    } catch (Exception e) {
        throw new IllegalStateException("Can't calculate sign of " + name, e);
    }
}
 
Example 6
Project: android-project-gallery   File: ApkSignUtils.java   View Source Code Vote up 6 votes
/**
 * 返回指定Apk文件的指纹信息
 * 
 * @param context
 * @param archiveFilePath
 * @param algorithm MD5 or SHA1
 * @return
 */
public static String getFingerprint(Context context, String archiveFilePath, String algorithm) {
	try {
		PackageInfo packageInfo = context.getPackageManager().getPackageArchiveInfo(archiveFilePath,
				PackageManager.GET_SIGNATURES);
		if (packageInfo == null) {
			return null;
		}
		Signature[] signs = packageInfo.signatures;
		MessageDigest md = MessageDigest.getInstance(algorithm);
		md.reset();
		md.update(signs[0].toByteArray());
		byte[] dataHash = md.digest();
		return bytes2HexString(dataHash);
	} catch (Exception e) {
		e.printStackTrace();
	}

	return null;
}
 
Example 7
Project: improved-journey   File: SecurityUtil.java   View Source Code Vote up 6 votes
/**
 * 加密 MD5 
 * 
 * @param strInput
 *            输入字符串
 * @return String
 * @throws Exception
 */
public final static String encoderMD5(String strInput) {
	if(strInput == null){
		return null;
	}
	MessageDigest messageDigest = null;
	try {
		messageDigest = MessageDigest.getInstance("MD5");
		messageDigest.reset();
		messageDigest.update(strInput.getBytes("UTF-8"));
	} catch (Exception ex) {
		logger.error("create MD5 error!",ex);
	}

	byte[] byteArray = messageDigest.digest();
	StringBuffer md5StrBuff = new StringBuffer();
	for (byte b : byteArray) {
		if (Integer.toHexString(0xFF & b).length() == 1) {
			md5StrBuff.append("0").append(Integer.toHexString(0xFF & b));
		} else {
			md5StrBuff.append(Integer.toHexString(0xFF & b));
		}
	}
	return md5StrBuff.toString();
}
 
Example 8
Project: LightSIP   File: WebSocketHttpHandshake.java   View Source Code Vote up 5 votes
static String computeRev13Response(String key) throws IOException {
	key = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
	MessageDigest md = null;
	try {
		md = MessageDigest.getInstance("SHA1");
		md.reset();
	} catch (NoSuchAlgorithmException ex) {
		// log.log(Level.SEVERE, "MD5 Algorithm not found", ex);
		ex.printStackTrace();
	}
	byte[] digest = md.digest(key.getBytes());
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	return new String(Base64Coder.encode(digest));
	
}
 
Example 9
Project: javaide   File: JKS.java   View Source Code Vote up 5 votes
private static byte[] decryptKey(byte[] encryptedPKI, byte[] passwd)
    throws UnrecoverableKeyException
{
    try
    {
        EncryptedPrivateKeyInfo epki =
            new EncryptedPrivateKeyInfo(encryptedPKI);
        byte[] encr = epki.getEncryptedData();
        byte[] keystream = new byte[20];
        System.arraycopy(encr, 0, keystream, 0, 20);
        byte[] check = new byte[20];
        System.arraycopy(encr, encr.length-20, check, 0, 20);
        byte[] key = new byte[encr.length - 40];
        MessageDigest sha = MessageDigest.getInstance("SHA1");
        int count = 0;
        while (count < key.length)
        {
            sha.reset();
            sha.update(passwd);
            sha.update(keystream);
            sha.digest(keystream, 0, keystream.length);
            for (int i = 0; i < keystream.length && count < key.length; i++)
            {
                key[count] = (byte) (keystream[i] ^ encr[count+20]);
                count++;
            }
        }
        sha.reset();
        sha.update(passwd);
        sha.update(key);
        if (!MessageDigest.isEqual(check, sha.digest()))
            throw new UnrecoverableKeyException("checksum mismatch");
        return key;
    }
    catch (Exception x)
    {
        throw new UnrecoverableKeyException(x.getMessage());
    }
}
 
Example 10
Project: javaide   File: JKS.java   View Source Code Vote up 5 votes
private static byte[] encryptKey(Key key, byte[] passwd)
    throws KeyStoreException
{
    try
    {
        MessageDigest sha = MessageDigest.getInstance("SHA1");
        SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
        byte[] k = key.getEncoded();
        byte[] encrypted = new byte[k.length + 40];
        byte[] keystream = rand.getSeed(20);
        System.arraycopy(keystream, 0, encrypted, 0, 20);
        int count = 0;
        while (count < k.length)
        {
            sha.reset();
            sha.update(passwd);
            sha.update(keystream);
            sha.digest(keystream, 0, keystream.length);
            for (int i = 0; i < keystream.length && count < k.length; i++)
            {
                encrypted[count+20] = (byte) (keystream[i] ^ k[count]);
                count++;
            }
        }
        sha.reset();
        sha.update(passwd);
        sha.update(k);
        sha.digest(encrypted, encrypted.length - 20, 20);
        // 1.3.6.1.4.1.42.2.17.1.1 is Sun's private OID for this
        // encryption algorithm.
        return new EncryptedPrivateKeyInfo("1.3.6.1.4.1.42.2.17.1.1",
            encrypted).getEncoded();
    }
    catch (Exception x)
    {
        throw new KeyStoreException(x.getMessage());
    }
}
 
Example 11
Project: Brevent   File: PlayServiceConnection.java   View Source Code Vote up 5 votes
static boolean verify(String tag, BigInteger modulus, String data, String signature) {
    if (TextUtils.isEmpty(data) || TextUtils.isEmpty(signature)) {
        return false;
    }
    BigInteger exponent = BigInteger.valueOf(0x10001);
    try {
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        sha1.update(data.getBytes());
        byte[] digest = sha1.digest();
        byte[] key = Base64.decode(signature, Base64.DEFAULT);
        byte[] sign = new BigInteger(1, key).modPow(exponent, modulus).toByteArray();
        for (int i = digest.length - 1, j = sign.length - 1; i >= 0; --i, --j) {
            sign[j] ^= digest[i];
        }
        sha1.reset();
        sha1.update(sign);
        digest = sha1.digest();
        for (int i = digest.length - 1; i >= 0; --i) {
            if (digest[i] != SHA_EXPECTED[i]) {
                return false;
            }
        }
        return true;
    } catch (IllegalArgumentException | GeneralSecurityException e) {
        Log.d(tag, "Can't verify");
    }
    return false;
}
 
Example 12
Project: openjdk-jdk10   File: CipherStreamClose.java   View Source Code Vote up 5 votes
public static Object streamDecrypt(byte[] data, SecretKey key,
    MessageDigest digest) throws Exception {

    Cipher decCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    decCipher.init(Cipher.DECRYPT_MODE, key);
    digest.reset();
    try (ByteArrayInputStream bis = new ByteArrayInputStream(data);
        DigestInputStream dis = new DigestInputStream(bis, digest);
        CipherInputStream cis = new CipherInputStream(dis, decCipher)) {

        try (ObjectInputStream ois = new ObjectInputStream(cis)) {
            return ois.readObject();
        }
    }
}
 
Example 13
Project: UpdateBuilder   File: SHA1Util.java   View Source Code Vote up 5 votes
public static String getSHA1(String toHash) {
	MessageDigest md = null;
	try {
		md = MessageDigest.getInstance("SHA1");
		md.reset();
		md.update(toHash.getBytes("UTF-8"));
	} catch (Exception ignored) {
		return "";
	}

	return String.format("%1$040x", new Object[] { new BigInteger(1, md.digest()) });
}
 
Example 14
Project: letv   File: MD5.java   View Source Code Vote up 5 votes
public static String toMd5(String md5Str) {
    String result = "";
    try {
        MessageDigest algorithm = MessageDigest.getInstance(CommonUtils.MD5_INSTANCE);
        algorithm.reset();
        algorithm.update(md5Str.getBytes("utf-8"));
        result = toHexString(algorithm.digest());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e2) {
        e2.printStackTrace();
    }
    return result;
}
 
Example 15
Project: jdk8u-jdk   File: CipherStreamClose.java   View Source Code Vote up 5 votes
public static Object streamDecrypt(byte[] data, SecretKey key,
    MessageDigest digest) throws Exception {

    Cipher decCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    decCipher.init(Cipher.DECRYPT_MODE, key);
    digest.reset();
    try (ByteArrayInputStream bis = new ByteArrayInputStream(data);
        DigestInputStream dis = new DigestInputStream(bis, digest);
        CipherInputStream cis = new CipherInputStream(dis, decCipher)) {

        try (ObjectInputStream ois = new ObjectInputStream(cis)) {
            return ois.readObject();
        }
    }
}
 
Example 16
Project: holon-core   File: TestJwt.java   View Source Code Vote up 5 votes
private static byte[] generateKey() throws Exception {
	String random = UUID.randomUUID().toString();
	MessageDigest algorithm = MessageDigest.getInstance("MD5");
	algorithm.reset();
	algorithm.update(random.getBytes());
	byte[] messageDigest = algorithm.digest();
	return Base64.getEncoder().encode(messageDigest);
}
 
Example 17
Project: sstable-adaptor   File: FBUtilities.java   View Source Code Vote up 4 votes
public static MessageDigest threadLocalMD5Digest()
{
    MessageDigest md = localMD5Digest.get();
    md.reset();
    return md;
}
 
Example 18
Project: apache-tomcat-7.0.73-with-comment   File: TestWebSocket.java   View Source Code Vote up 4 votes
@Test
public void testKey() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(new ApplicationListener(
            TesterEchoServer.Config.class.getName(), false));

    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketClient client= new WebSocketClient(getPort());

    // Send the WebSocket handshake
    client.writer.write("GET " + TesterEchoServer.Config.PATH_BASIC + " HTTP/1.1" + CRLF);
    client.writer.write("Host: foo" + CRLF);
    client.writer.write("Upgrade: websocket" + CRLF);
    client.writer.write("Connection: upgrade" + CRLF);
    client.writer.write("Sec-WebSocket-Version: 13" + CRLF);
    client.writer.write("Sec-WebSocket-Key: TODO" + CRLF);
    client.writer.write(CRLF);
    client.writer.flush();

    // Make sure we got an upgrade response
    String responseLine = client.reader.readLine();
    assertTrue(responseLine.startsWith("HTTP/1.1 101"));

    String accept = null;
    String responseHeaderLine = client.reader.readLine();
    while (!responseHeaderLine.equals("")) {
        if(responseHeaderLine.startsWith("Sec-WebSocket-Accept: ")) {
            accept = responseHeaderLine.substring(responseHeaderLine.indexOf(':')+2);
            break;
        }
        responseHeaderLine = client.reader.readLine();
    }
    assertTrue(accept != null);
    MessageDigest sha1Helper = MessageDigest.getInstance("SHA1");
    sha1Helper.reset();
    sha1Helper.update("TODO".getBytes(B2CConverter.ISO_8859_1));
    String source = Base64.encode(sha1Helper.digest(WS_ACCEPT));
    assertEquals(source,accept);

    sha1Helper.reset();
    sha1Helper.update("TOD".getBytes(B2CConverter.ISO_8859_1));
    source = Base64.encode(sha1Helper.digest(WS_ACCEPT));
    assertFalse(source.equals(accept));
    // Finished with the socket
    client.close();
}
 
Example 19
Project: openjdk-jdk10   File: KeyProtector.java   View Source Code Vote up 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 20
Project: parabuild-ci   File: StringUtils.java   View Source Code Vote up 3 votes
/**
 * Digests password with MD5 and encodes it as a hex String.
 *
 * @param password to digest.
 *
 * @return hex encoded password digest.
 */
public static String digest(final String password) throws NoSuchAlgorithmException {
  final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
  messageDigest.reset();
  messageDigest.update(password.trim().toLowerCase().getBytes());
  return encodeToHex(messageDigest.digest());
}