简体   繁体   English

在C#上获取文件的SHA1二进制base64哈希

[英]Get SHA1 binary base64 hash of a file on C#

I am thinking on creating a program on C# to get the SHA1 binary base64 hash of a series of very large files. 我正在考虑在C#上创建一个程序来获取一系列非常大的文件的SHA1二进制base64哈希。

Right now I can accomplish that by running this instruction on OpenSSL: 现在我可以通过在OpenSSL上运行此指令来实现这一点:

openssl sha1 -binary FILENAME | openssl sha1 -binary FILENAME | openssl base64 openssl base64

however I haven´t found references for the "binary" and "base64" parts to obtain the same result with C#. 但是我没有找到“二进制”和“base64”部分的引用来获得与C#相同的结果。

Is it possible? 可能吗? Maybe call openssl inside C#? 也许在C#中调用openssl?

Thank you. 谢谢。

You need to use the Convert.ToBase64String method and the System.IO namespace to read binary: 您需要使用Convert.ToBase64String方法和System.IO命名空间来读取二进制文件:

string GetBase64EncodedSHA1Hash(string filename)
{
    using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
    using (SHA1Managed sha1 = new SHA1Managed())
    {
        return Convert.ToBase64String(sha1.ComputeHash(fs));
    }
}

The easiest way to do this is Get-FileHash which has been available since PS 4.0 最简单的方法是从PS 4.0开始提供Get-FileHash

$ echo "Hello world" >1.tm
$
$ Get-FileHash 1.tm

Algorithm       Hash                                                                   
Path
---------       ----                                                                   ----
SHA256          B995A2FAFFB3F27C632CE037BDB2ADB04EC3E578D0FA794BA50CFC16F0F219BF       
C:\scratch\1.tm


$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM