分享

OAuth协议中的HMAC_SHA1算法

 实力决定地位 2012-03-30
 本人抄袭一篇java进行改变成C#的。。运行结构完全和java一样所以证明完全没有问题。。尽心的用
public static byte[] getHmacSHA1(String data, String key)
        {

            byte[] ipadArray = new byte[64];
            byte[] opadArray = new byte[64];
            byte[] keyArray = new byte[64];
            System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();

           // SHA1 sha1 = null;
            int ex = key.Length;
            if (key.Length > 64)
            {
                byte[] temp = sha1.ComputeHash(strToToHexByte(key));
                ex = temp.Length;
                for (int i = 0; i < ex; i++)
                {
                    keyArray[i] = temp[i];
                }
            }
            else
            {
                byte[] temp = strToToHexByte(key);
                for (int i = 0; i < temp.LongLength; i++)
                {
                    keyArray[i] = temp[i];
                }
            }

            for (int i = ex; i < 64; i++)
            {
                keyArray[i] = 0;
            }
            for (int j = 0; j < 64; j++)
            {
                ipadArray[j] = (byte)(keyArray[j] ^ 0x36);
                opadArray[j] = (byte)(keyArray[j] ^ 0x5C);
            }
            byte[] tempResult = sha1.ComputeHash(join(ipadArray, strToToHexByte(data)));

            return sha1.ComputeHash(join(opadArray, tempResult));

 

        }

        private static byte[] join(byte[] b1, byte[] b2)
        {
            int length = b1.Length + b2.Length;
            byte[] newer = new byte[length];
            for (int i = 0; i < b1.LongLength; i++)
            {
                newer[i] = b1[i];
            }
            for (int i = 0; i < b2.LongLength; i++)
            {
                newer[i + b1.LongLength] = b2[i];
            }
            return newer;
        }
调用的时候转换成base64
byte[] sb= HMAC_SHA1.getHmacSHA1("456", "123");
Convert.ToBase64String(sb).
输出结果:arl7onB4MoLePp7oTLNSrhxAOWw=

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多