java - 是否可以在 Java 中将 String 转换为 NTLM 哈希?

标签 java hash

是否可以将 String 转换为 NTLM 哈希?是否有我可以导入的 Java 库,或者是否有我可以用来获取它的方法?

最佳答案

我写了这个实用类:

import jcifs.smb.NtlmPasswordAuthentication;

/**
 * NTLM passwords encoding.
 * 
 * This implementation depends on the JCIFS library.
 */
public class NTLMPassword {

    private final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();

    private NTLMPassword() {
        // No need to instantiate this class
    }

    /**
     * Return NTLM hash for a given string.
     * 
     * See https://lists.samba.org/archive/jcifs/2015-February/010258.html
     * 
     * @param value
     *            the string to hash.
     * @return the NTLM hash for the given string.
     */
    public static String encode(String value) {
        String s = (value != null) ? value : "";
        byte[] hash = NtlmPasswordAuthentication.nTOWFv1(s);
        return bytesToHex(hash).toUpperCase();
    }

    /**
     * See https://stackoverflow.com/a/9855338/1314986
     */
    private static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }
}

此代码使用 JCIFS 库。如果您使用 Maven,请包含以下依赖项:

<dependency>
    <groupId>org.codelibs</groupId>
    <artifactId>jcifs</artifactId>
    <version>1.3.18.2</version>
</dependency>

您可以使用以下测试验证此代码:

@Test
public void testEncode() throws Exception {
    assertEquals("D36D0FC68CEDDAF7E180A6AE71096B35", NTLMPassword.encode("DummyPassword"));
}

关于java - 是否可以在 Java 中将 String 转换为 NTLM 哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41381556/

相关文章:

java - 将字符串转换为散列,然后再重新生成字符串

php - 检索 redis 哈希数据

java - 数组和 vector 的内存分配如何工作?

java - 在 TextView 中显示来自 SQLite 的项目

algorithm - 单个 "1"位的 SHA-256 哈希值是多少?

ruby-on-rails - 如何将 yaml 文件解析为 ruby​​ 哈希和/或数组?

java - 如何同时在两个数组中找到相同的 byte[]-objects?

java - onBackPressed() 方法在 Android 抽屉导航中无法按预期工作

java - 在请求 Dispatcher.forward 方法之后从另一个 Servlet 调用一个 Servlet

java - 寻找数组中最短的项?