SHA3​​84 PHP代码转换为C#

时间:2016-02-18 11:12:32

标签: c# php .net hash

我有一些问题将这个PHP代码翻译成C#:

$hash = hash('sha384', $string_to_hash, true); 
$base64Hash = strtr(base64_encode($hash), '+/', '-_');
你能帮帮我吗? 谢谢!

编辑:我正在使用整个PHP代码更新此帖子以转换为C#,因为我无法使用两种语言获得相同的哈希令牌

$host = "100.200.100.200"; 
$url= "http://".$host.":1935/";
$stream = "vod/_definst_/test.smil"; 
$start = time();
$end = strtotime("+30 minutes");
$secret = "abcde";
$tokenName = "wowzatoken";

$hash = hash('sha384', $stream."?".$secret."&{$tokenName}endtime=".$end."&{$tokenName}starttime=".$start, true); 
$base64Hash = strtr(base64_encode($hash), '+/', '-_');
$params = array("{$tokenName}starttime=".$start, "{$tokenName}endtime=".$end, "{$tokenName}hash=".$base64Hash);

$playbackURL = $url.$stream."/playlist.m3u8?";

foreach($params as $entry){
    $playbackURL.= $entry."&";
}

$playbackURL = preg_replace("/(\&)$/","", $playbackURL);

echo $playbackURL;

1 个答案:

答案 0 :(得分:0)

我不擅长PHP,所以我不确定strtr函数。但我已尝试解决您的问题,并在下面提供一些代码。试试吧。

 class Program
{
    public static string Base64Decode(string base64EncodedData)
    {
        var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
        return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
    }

    public static string Base64Encode(string plainText)
    {
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
        return System.Convert.ToBase64String(plainTextBytes);
    }

    public static string GetString(byte[] bytes)
    {
        char[] chars = new char[bytes.Length / sizeof(char)];
        System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
        return new string(chars);
    }

    public static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

    static void Main(string[] args)
    {
        string code = "SecretCode";

        byte[] data = new byte[code.Length];
        byte[] result;
        data = GetBytes(code);
        SHA384 shaM = new SHA384Managed();
        result = shaM.ComputeHash(data);

        string encodedString = GetString(result);

        string ans = Base64Encode(encodedString);

        ans = ans.Replace('+','-').Replace('/','_');

        Console.Write(ans);
        Console.Read();
    }
}