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

The following examples show how to use java.security.MessageDigest#reset() . 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: StressTestDirectAttach.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static String createMD5Password(String password) {
    MessageDigest md5;

    try {
        md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new CloudRuntimeException("Error", e);
    }

    md5.reset();
    BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes()));

    // make sure our MD5 hash value is 32 digits long...
    StringBuffer sb = new StringBuffer();
    String pwStr = pwInt.toString(16);
    int padding = 32 - pwStr.length();
    for (int i = 0; i < padding; i++) {
        sb.append('0');
    }
    sb.append(pwStr);
    return sb.toString();
}
 
Example 2
Source File: PasswordUtil.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
public String encrypt(String password) {
    byte[] plainText = password.getBytes();
    StringBuilder sb = new StringBuilder();
    try {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.reset();
        md.update(plainText);
        byte[] encodedPassword = md.digest();
        for (int i = 0; i < encodedPassword.length; i++) {
            if ((encodedPassword[i] & 0xff) < 0x10) {
                sb.append("0");
            }

            sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}
 
Example 3
Source File: MTProto.java    From TelegramApi with MIT License 6 votes vote down vote up
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 4
Source File: MysqlNativePasswordUtil.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
/**
 * Calculates a hash of the user's password.
 *
 * @param password the user's password
 * @param salt     the salt send from the server in the {@link ClientHandshakePacket} packet.
 * @return the hashed password
 */
public static byte[] hashPassword(String password, byte[] salt) {
	try {
		MessageDigest md = MessageDigest.getInstance("SHA-1");

		byte[] hashedPassword = md.digest(password.getBytes());

		md.reset();
		byte[] doubleHashedPassword = md.digest(hashedPassword);

		md.reset();
		md.update(salt, 0, 20);
		md.update(doubleHashedPassword);

		byte[] hash = md.digest();
		for (int i = 0; i < hash.length; i++) {
			hash[i] = (byte) (hash[i] ^ hashedPassword[i]);
		}
		return hash;
	} catch (NoSuchAlgorithmException e) {
		throw new RuntimeException(e);
	}
}
 
Example 5
Source File: VDUtility.java    From NewsMe with Apache License 2.0 6 votes vote down vote up
/**
 * md5
 * 
 * @param str
 * @return
 */
public static String md5(String str) {
	try {
		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		messageDigest.reset();
		messageDigest.update(str.getBytes("UTF-8"));
		byte[] byteArray = messageDigest.digest();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
				sb.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			} else {
				sb.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		}

		return sb.toString();
	} catch (Exception e) {
		e.printStackTrace();
	}

	return str;
}
 
Example 6
Source File: UnlockActivity.java    From Augendiagnose with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a hash value of a String.
 *
 * @param input The input string.
 * @return The hash value.
 */
private static String createHash(@NonNull final String input) {
	try {
		MessageDigest md = MessageDigest.getInstance("SHA1");
		md.reset();
		byte[] buffer = input.getBytes("UTF-8");
		md.update(buffer);
		byte[] digest = md.digest();

		String hexStr = "";
		for (int i = 0; i < digest.length; i++) {
			hexStr += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1); // MAGIC_NUMBER
		}
		return hexStr;
	}
	catch (Exception e) {
		return null;
	}
}
 
Example 7
Source File: SSHAPasswordEncryptor.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
public byte[] encrypt(byte[] password) {
  byte[] salt = new byte[6];
  SECURE_RANDOM.nextBytes(salt);
  try {
    byte[] buff = new byte[password.length + salt.length];
    System.arraycopy(password, 0, buff, 0, password.length);
    System.arraycopy(salt, 0, buff, password.length, salt.length);

    byte[] res = new byte[20 + salt.length];
    MessageDigest md = MessageDigest.getInstance("SHA");
    md.reset();
    System.arraycopy(md.digest(buff), 0, res, 0, 20);
    System.arraycopy(salt, 0, res, 20, salt.length);

    return (SSHA_PREFIX + Base64.getEncoder().encodeToString(res)).getBytes();
  } catch (NoSuchAlgorithmException e) {
    throw new RuntimeException(e.getLocalizedMessage());
  }
}
 
Example 8
Source File: ChecksumHelper.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
private static byte[] compute(File f, String algorithm) throws IOException {

        try (InputStream is = new FileInputStream(f)) {
            MessageDigest md = getMessageDigest(algorithm);
            md.reset();

            byte[] buf = new byte[BUFFER_SIZE];
            int len = 0;
            while ((len = is.read(buf)) != -1) {
                md.update(buf, 0, len);
            }
            return md.digest();
        }
    }
 
Example 9
Source File: StringUtils.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Get the MD5 sum of a content passed as String
 *
 * @param data
 * @return the MD5 sum
 */
public static String md5sum( String data ) {

    byte[] defaultBytes = data.getBytes();
    try {
        MessageDigest algorithm = MessageDigest.getInstance("MD5");
        algorithm.reset();
        algorithm.update(defaultBytes);
        byte messageDigest[] = algorithm.digest();

        return byteArray2Hex(messageDigest);
    } catch (NoSuchAlgorithmException nsae) {
        throw new RuntimeException(nsae);
    }
}
 
Example 10
Source File: Sha.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] encrypt(byte[] source, final byte[] key) throws GeneralSecurityException {
    // 获得SHA摘要算法的 MessageDigest 对象
    MessageDigest md = MessageDigest.getInstance("SHA");
    md.reset();
    // 使用指定的字节更新摘要
    md.update(source);
    // 获得密文
    return md.digest();
}
 
Example 11
Source File: SecureUtil.java    From unionpay with MIT License 5 votes vote down vote up
/**
 * sha1计算.
 * 
 * @param data
 *            待计算的数据
 * @return 计算结果
 */
private static byte[] sha1(byte[] data) {
	MessageDigest md = null;
	try {
		md = MessageDigest.getInstance(ALGORITHM_SHA1);
		md.reset();
		md.update(data);
		return md.digest();
	} catch (Exception e) {
		LogUtil.writeErrorLog("SHA1计算失败", e);
		return null;
	}
}
 
Example 12
Source File: SecurityUtil.java    From canal with Apache License 2.0 5 votes vote down vote up
public static final String scrambleGenPass(byte[] pass) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    byte[] pass1 = md.digest(pass);
    md.reset();
    byte[] pass2 = md.digest(pass1);
    return SecurityUtil.byte2HexStr(pass2);
}
 
Example 13
Source File: TorrentUtils.java    From mldht with Mozilla Public License 2.0 5 votes vote down vote up
public static Key infohash(ByteBuffer rawTorrent) {
	
	Tokenizer t = new Tokenizer();
	PathMatcher m = new PathMatcher("info");
	m.tokenizer(t);
	
	ByteBuffer rawInfo = m.match(rawTorrent.duplicate());
	
	MessageDigest dig = ThreadLocalUtils.getThreadLocalSHA1();
	dig.reset();
	dig.update(rawInfo);
	return new Key(dig.digest());
	
}
 
Example 14
Source File: BUtility.java    From appcan-android with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String getMD5Code(String[] value) {
    if (value == null || value.length == 0) {
        return null;
    }
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();
        for (String va : value) {
            if (va == null) {
                va = "";
            }
            md.update(va.getBytes());
        }
        byte[] md5Bytes = md.digest();
        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();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 15
Source File: LaunchApp.java    From PUMA with Apache License 2.0 5 votes vote down vote up
private String getTextDigest(CharSequence text) {
	MessageDigest m = null;

	try {
		m = MessageDigest.getInstance("MD5");
	} catch (NoSuchAlgorithmException e) {
		/* ignore*/
	}

	if (m == null) {
		return "";
	}

	String plaintext = "";

	if (text != null) {
		plaintext = text.toString();
	}

	m.reset();
	m.update(plaintext.getBytes());
	byte[] digest = m.digest();
	BigInteger bigInt = new BigInteger(1, digest);
	String hashtext = bigInt.toString(16);

	// Now we need to zero pad it if you actually want the full 32 chars.
	while (hashtext.length() < 32) {
		hashtext = "0" + hashtext;
	}

	return HashIdDictionary.add(hashtext);
}
 
Example 16
Source File: PasswordAuthPlugin.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
public static byte[] passwdSha256(String pass, HandshakeV10Packet hs) throws NoSuchAlgorithmException {
    if (pass == null || pass.length() == 0) {
        return null;
    }
    MessageDigest md = null;
    int cachingSha2DigestLength = 32;

    byte[] passwd = pass.getBytes();
    try {
        md = MessageDigest.getInstance("SHA-256");
        byte[] dig1 = new byte[cachingSha2DigestLength];
        byte[] dig2 = new byte[cachingSha2DigestLength];
        md.update(passwd, 0, passwd.length);
        md.digest(dig1, 0, cachingSha2DigestLength);
        md.reset();
        md.update(dig1, 0, dig1.length);
        md.digest(dig2, 0, cachingSha2DigestLength);
        md.reset();

        int sl1 = hs.getSeed().length;
        int sl2 = hs.getRestOfScrambleBuff().length;
        byte[] seed = new byte[sl1 + sl2];
        System.arraycopy(hs.getSeed(), 0, seed, 0, sl1);
        System.arraycopy(hs.getRestOfScrambleBuff(), 0, seed, sl1, sl2);
        md.update(dig2, 0, dig1.length);
        md.update(seed, 0, seed.length);
        byte[] scramble1 = new byte[cachingSha2DigestLength];
        md.digest(scramble1, 0, cachingSha2DigestLength);

        byte[] mysqlScrambleBuff = new byte[cachingSha2DigestLength];
        xorString(dig1, mysqlScrambleBuff, scramble1, cachingSha2DigestLength);
        seedTotal = seed;

        return mysqlScrambleBuff;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return passwd;
}
 
Example 17
Source File: Md5Utils.java    From es with Apache License 2.0 5 votes vote down vote up
private static byte[] md5(String s) {
    MessageDigest algorithm;
    try {
        algorithm = MessageDigest.getInstance("MD5");
        algorithm.reset();
        algorithm.update(s.getBytes("UTF-8"));
        byte[] messageDigest = algorithm.digest();
        return messageDigest;
    } catch (Exception e) {
        LOGGER.error("MD5 Error...", e);
    }
    return null;
}
 
Example 18
Source File: Hmac.java    From EosCommander with MIT License 4 votes vote down vote up
private static byte[] hash(MessageDigest digest, byte[] data1, byte[] data2) {
   digest.reset();
   digest.update(data1, 0, data1.length);
   digest.update(data2, 0, data2.length);
   return digest.digest();
}
 
Example 19
Source File: NetworkModelImpl.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@Override
public List<String[]> generateVmData(String userData, String serviceOffering, long datacenterId,
                                     String vmName, String vmHostName, long vmId, String vmUuid,
                                     String guestIpAddress, String publicKey, String password, Boolean isWindows) {

    DataCenterVO dcVo = _dcDao.findById(datacenterId);
    final String zoneName = dcVo.getName();

    IPAddressVO publicIp = _ipAddressDao.findByAssociatedVmId(vmId);

    final List<String[]> vmData = new ArrayList<String[]>();

    if (userData != null) {
        vmData.add(new String[]{USERDATA_DIR, USERDATA_FILE, userData});
    }
    vmData.add(new String[]{METATDATA_DIR, SERVICE_OFFERING_FILE, StringUtils.unicodeEscape(serviceOffering)});
    vmData.add(new String[]{METATDATA_DIR, AVAILABILITY_ZONE_FILE, StringUtils.unicodeEscape(zoneName)});
    vmData.add(new String[]{METATDATA_DIR, LOCAL_HOSTNAME_FILE, StringUtils.unicodeEscape(vmHostName)});
    vmData.add(new String[]{METATDATA_DIR, LOCAL_IPV4_FILE, guestIpAddress});

    String publicIpAddress = guestIpAddress;
    String publicHostName = StringUtils.unicodeEscape(vmHostName);

    if (dcVo.getNetworkType() != DataCenter.NetworkType.Basic) {
        if (publicIp != null) {
            publicIpAddress = publicIp.getAddress().addr();
            publicHostName = publicIp.getAddress().addr();
        } else {
            publicHostName = null;
        }
    }
    vmData.add(new String[]{METATDATA_DIR, PUBLIC_IPV4_FILE, publicIpAddress});
    vmData.add(new String[]{METATDATA_DIR, PUBLIC_HOSTNAME_FILE, publicHostName});

    if (vmUuid == null) {
        vmData.add(new String[]{METATDATA_DIR, INSTANCE_ID_FILE, vmName});
        vmData.add(new String[]{METATDATA_DIR, VM_ID_FILE, String.valueOf(vmId)});
    } else {
        vmData.add(new String[]{METATDATA_DIR, INSTANCE_ID_FILE, vmUuid});
        vmData.add(new String[]{METATDATA_DIR, VM_ID_FILE, vmUuid});
    }

    vmData.add(new String[]{METATDATA_DIR, PUBLIC_KEYS_FILE, publicKey});

    String cloudIdentifier = _configDao.getValue("cloud.identifier");
    if (cloudIdentifier == null) {
        cloudIdentifier = "";
    } else {
        cloudIdentifier = "CloudStack-{" + cloudIdentifier + "}";
    }
    vmData.add(new String[]{METATDATA_DIR, CLOUD_IDENTIFIER_FILE, cloudIdentifier});

    if (password != null && !password.isEmpty() && !password.equals("saved_password")) {

        // Here we are calculating MD5 checksum to reduce the over head of calculating MD5 checksum
        // in windows VM in password reset script.

        if (isWindows) {
            MessageDigest md5 = null;
            try {
                md5 = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                s_logger.error("Unexpected exception " + e.getMessage(), e);
                throw new CloudRuntimeException("Unable to get MD5 MessageDigest", e);
            }
            md5.reset();
            md5.update(password.getBytes(StringUtils.getPreferredCharset()));
            byte[] digest = md5.digest();
            BigInteger bigInt = new BigInteger(1, digest);
            String hashtext = bigInt.toString(16);

            vmData.add(new String[]{PASSWORD_DIR, PASSWORD_CHECKSUM_FILE, hashtext});
        }

        vmData.add(new String[]{PASSWORD_DIR, PASSWORD_FILE, password});
    }

    return vmData;
}
 
Example 20
Source File: AuthenticationServiceBase.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
static protected String encryptPassword(String userName,
	    String plainTxtUserPassword, boolean forceEncrypt,
	    boolean v2Encrypt, boolean v3Encrypt) throws StandardException
// GemStone changes END
	{
		if (plainTxtUserPassword == null)
			return null;
		
// GemStone changes BEGIN
                if (!forceEncrypt) {
                  if (
                      isEncrypted(plainTxtUserPassword)) {
                    // this is already encrypted once at the originating node & we are
                    // setting here locally.
                    if (GemFireXDUtils.TraceAuthentication) {
                      SanityManager.DEBUG_PRINT(AuthenticationTrace,
                          "Skipping encryption as it must be encrypted from origin - "
                              + plainTxtUserPassword);
                    }
                    return plainTxtUserPassword;
                  }
                }
// GemStone changes END

		MessageDigest algorithm = null;
		String algoName = v3Encrypt ? "SHA-256" : "SHA-1";
		try
		{
			algorithm = MessageDigest.getInstance(algoName);
		} catch (NoSuchAlgorithmException nsae)
		{
		  throw StandardException.newException(SQLState.ENCRYPTION_NOSUCH_ALGORITHM,
		      algoName, "default");
		}

		algorithm.reset();
		byte[] bytePasswd = StringUtil.toHexByte(
		    plainTxtUserPassword, 0, plainTxtUserPassword.length());
// GemStone changes BEGIN
		if (v3Encrypt || v2Encrypt) {
		  // salt with the user name
		  if (userName == null || userName.length() == 0) {
		    userName = "USER";
		  }
		  else {
		    // normalize the userName
		    userName = IdUtil.getUserAuthorizationId(userName);
		  }
		  try {
		    GemFireXDUtils.updateCipherKeyBytes(bytePasswd,
		        userName.getBytes("UTF-8"));
		  } catch (UnsupportedEncodingException ue) {
		    // never expected to happen except in broken JVMs
		    throw new IllegalStateException(ue.getMessage(), ue);
		  }
		}
// GemStone changes END
		algorithm.update(bytePasswd);
		byte[] encryptVal = algorithm.digest();
		String hexString = (v3Encrypt ? ID_PATTERN_NEW_SCHEME_V3
		    : (v2Encrypt ? ID_PATTERN_NEW_SCHEME_V2
		        : ID_PATTERN_NEW_SCHEME_V1)) + StringUtil.toHexString(
		        encryptVal, 0, encryptVal.length);
                if (SanityManager.DEBUG_ON("__PINT__")) {
                  SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_AUTHENTICATION,
                      " encrypting with v2encrypt=" + v2Encrypt + plainTxtUserPassword + " to " + hexString, new Throwable("SB"));
                }
		return (hexString);

	}