启用两因素身份验证时,基于Netsuite令牌的身份验证出现无效的登录错误

时间:2019-04-04 10:05:07

标签: c# authentication netsuite suitetalk

我们正在尝试为现有的netsuite集成实施基于令牌的身份验证,并且对于未启用两因素身份验证的netsuite帐户,新的实现正在按预期工作。

从netsuite文档中,我们了解到启用了两因素身份验证的帐户无需多加注意。根据文档,我们需要生成一个OTP并将其与Authorization标头一起发送。对于生成OTP网络套件,建议遵循此link。我们已经实现了等效的C#。但是,当在Authorization标头中使用生成的OTP时,我们收到无效的登录尝试错误。 Netsuite登录审核日志显示“ wrongsecondfator ”。下面是我们的实现

    public  string generateTOTP(string key,int returnDigits)
    {
        ulong T = new TOTP_SHA1(key).CounterNow();
        string time = T.ToString("X");
        string result = null;

        // Using the counter
        // First 8 bytes are for the movingFactor
        // Compliant with base RFC 4226 (HOTP)
        while (time.Length < 16)
            time = "0" + time;
        var hexString1 = ConvertStringToHex(key,Encoding.Default);
        byte[] msg = hexStr2Bytes(time);
        byte[] k = hexStr2Bytes(hexString1);


        byte[] hash = hmac_sha(k, msg);

        // put selected bytes into result int
        int offset = hash[hash.Length - 1] & 0xf;

        int binary =
            ((hash[offset] & 0x7f) << 24) |
            ((hash[offset + 1] & 0xff) << 16) |
            ((hash[offset + 2] & 0xff) << 8) |
            (hash[offset + 3] & 0xff);

        int otp = binary % DIGITS_POWER[returnDigits];

        result = Convert.ToString(otp);
        while (result.Length < returnDigits)
        {
            result = "0" + result;
        }
        return result;
    }

    private static int[] DIGITS_POWER { get; set; } = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 };
    private byte[] K;
    public TOTP_SHA1(string tfasecretkey)
    {
        K = Encoding.ASCII.GetBytes(tfasecretkey);
    }

    public UInt64 CounterNow(int T1 = 30)
    {
        var secondsSinceEpoch = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
        return (UInt64)Math.Floor(secondsSinceEpoch / T1);
    }

    private static byte[] hexStr2Bytes(String hex)
    {
        return Enumerable.Range(0, hex.Length)
                 .Where(x => x % 2 == 0)
                 .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                 .ToArray();
    }

    private static byte[] hmac_sha(byte[] keyBytes,byte[] text)
    {
        var hmac = HMACSHA512.Create();
        hmac.Key = keyBytes;
        return hmac.ComputeHash(text);
    }

    public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
    {
        Byte[] stringBytes = encoding.GetBytes(input);
        StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
        foreach (byte b in stringBytes)
        {
            sbBytes.AppendFormat("{0:X2}", b);
        }
        return sbBytes.ToString();
    }

netsuite支持团队关于此错误是otp生成的反馈不符合要求。

任何帮助将不胜感激。预先感谢。

0 个答案:

没有答案