如何使用SHA2验证数据完整性?

发布于 2024-10-13 04:14:05 字数 1238 浏览 14 评论 0原文

package abc.xyz;
import java.io.UnsupportedEncodingException; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 

public class SHA2{ 

    private static String convertToHex(byte[] data) { 
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) { 
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do { 
                if ((0 <= halfbyte) && (halfbyte <= 9)) 
                    buf.append((char) ('0' + halfbyte));
                else 
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        } 
        return buf.toString();
    }      
public static String SHA2(String text) 
            throws NoSuchAlgorithmException, UnsupportedEncodingException  { 

        MessageDigest mesd;
        mesd = MessageDigest.getInstance("SHA-2");
        byte[] sha2hash = new byte[40];
        mesd.update(text.getBytes("iso-8859-1"), 0, text.length());
        sha2hash = mesd.digest();//error
        return convertToHex(sha2hash);
    } }

我在实现digest()时遇到错误;

package abc.xyz;
import java.io.UnsupportedEncodingException; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 

public class SHA2{ 

    private static String convertToHex(byte[] data) { 
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) { 
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do { 
                if ((0 <= halfbyte) && (halfbyte <= 9)) 
                    buf.append((char) ('0' + halfbyte));
                else 
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        } 
        return buf.toString();
    }      
public static String SHA2(String text) 
            throws NoSuchAlgorithmException, UnsupportedEncodingException  { 

        MessageDigest mesd;
        mesd = MessageDigest.getInstance("SHA-2");
        byte[] sha2hash = new byte[40];
        mesd.update(text.getBytes("iso-8859-1"), 0, text.length());
        sha2hash = mesd.digest();//error
        return convertToHex(sha2hash);
    } }

I am getting error in implementing digest();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

醉南桥 2024-10-20 04:14:05

SHA-2 本身并不是一种算法。维基百科:

SHA-2 是一组加密哈希函数(SHA-224、SHA-256、SHA-384、SHA-512)

我认为除了 SHA-224 之外的所有函数都应该可用。

public static String SHA2(String text) 
    throws NoSuchAlgorithmException, UnsupportedEncodingException  { 

  MessageDigest mesd = MessageDigest.getInstance("SHA-256");
  byte[] bytes = text.getBytes("iso-8859-1");
  mesd.update(bytes, 0, bytes.length);
  byte[] sha2hash = mesd.digest();
  return convertToHex(sha2hash);
} 

此外,您创建的字节数组不是必需的。 digest() 方法返回一个数组本身。赋值运算符从不将结果写入现有数组。当然,除非您指定索引。

还有一件事。调用 update(..) 时我不会使用 text.length(),因为它不一定与结果字节数组的长度相同。这主要是 UTF-8 等多字节字符编码的情况。对于无法映射的字符也可能会发生这种情况,具体取决于您选择的策略。嗯,重点是:你不需要知道我在说什么。只需使用数组的 .length 来保存:)

SHA-2 isn't an algorithm itself. Wikipedia:

SHA-2 is a set of cryptographic hash functions (SHA-224, SHA-256, SHA-384, SHA-512)

I think all but SHA-224 should be available.

public static String SHA2(String text) 
    throws NoSuchAlgorithmException, UnsupportedEncodingException  { 

  MessageDigest mesd = MessageDigest.getInstance("SHA-256");
  byte[] bytes = text.getBytes("iso-8859-1");
  mesd.update(bytes, 0, bytes.length);
  byte[] sha2hash = mesd.digest();
  return convertToHex(sha2hash);
} 

Additionally, the byte array you create isn't necessary. The digest() method returns an array itself. The assignment operator never writes a result into an existing array. Unless you specify an index of course.

One more thing. I wouldn't use text.length() when calling update(..) as it's not necessarily the same as the length of the resulting byte array. This is mainly the case for multibyte character encoding like UTF-8. It might also occur for characters that can't be mapped, depending on your strategy of choice. Well, the main point is though: you don't need to know what I'm talking about. Simply use an array's .length instead to be save :)

鱼窥荷 2024-10-20 04:14:05

您需要指定您要使用的 SHA-2 变体:SHA-256或 SHA-512。使用它们作为摘要名称。

You need to specify which SHA-2 variant you'd like to use: SHA-256 or SHA-512. Use those as the digest names.

離殇 2024-10-20 04:14:05

如果您还没有阅读过,我建议您阅读 SUN JCA 文档,特别是 消息摘要。如果您查看默认的SUN 提供程序,您会注意到 SHA-2 实际上并不存在,也许可以尝试“SHA-512”。

尝试:

String message = "Some Message";

MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");

messageDigest.update(message.getBytes("UTF-16BE"));
byte[] digest = messageDigest.digest();

StringBuffer digestInHex = new StringBuffer();

for (int i = 0, l = digest.length; i < l; i++) {
    // Preserve the bit representation when casting to integer.
    int intRep = digest[i] & 0xFF;
    // Add leading zero if value is less than 0x10.
    if (intRep < 0x10)  digestInHex.append('\u0030');
    // Convert value to hex.
    digestInHex.append(Integer.toHexString(intRep));
}

System.out.println(digestInHex.toString());

If you haven't already I'd recommend reading the SUN docs on JCA, particularly the MessageDigest. If you look at the default SUN providers, you'll notice that SHA-2 doesn't actually exist, perhaps try 'SHA-512' instead.

Try:

String message = "Some Message";

MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");

messageDigest.update(message.getBytes("UTF-16BE"));
byte[] digest = messageDigest.digest();

StringBuffer digestInHex = new StringBuffer();

for (int i = 0, l = digest.length; i < l; i++) {
    // Preserve the bit representation when casting to integer.
    int intRep = digest[i] & 0xFF;
    // Add leading zero if value is less than 0x10.
    if (intRep < 0x10)  digestInHex.append('\u0030');
    // Convert value to hex.
    digestInHex.append(Integer.toHexString(intRep));
}

System.out.println(digestInHex.toString());
も让我眼熟你 2024-10-20 04:14:05

什么错误? “sha1hash无法解析”?您错过了声明变量。在 eclipse 中按 ctrl-1 即可完成工作。 sha2hash 怎么样?我想说,这样的变量应该只有一个。文本和文本字符串怎么样?又一个自我困惑?

顺便说一句,不存在“SHA-2”这样的东西。它是一系列函数,例如包含 SHA-256。所以尝试这样的事情:

public static byte[] sha2(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    final MessageDigest mesd = MessageDigest.getInstance("SHA-256");
    mesd.update(text.getBytes("iso-8859-1"), 0, text.length());
    return mesd.digest();
}

What error? "sha1hash cannot be resolved"? You missed to declare the variable. Pressing ctrl-1 in eclipse does the job. What about sha2hash? I'd say, there should be only one such variable. What about text and textstring? Another self-confusion?

Btw., there's no such thing as "the SHA-2". It's a family of functions, containing e.g., SHA-256. So try something like this:

public static byte[] sha2(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    final MessageDigest mesd = MessageDigest.getInstance("SHA-256");
    mesd.update(text.getBytes("iso-8859-1"), 0, text.length());
    return mesd.digest();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文