【问题标题】:String from web.config AppSettings convert to byte[]来自 web.config AppSettings 的字符串转换为 byte[]
【发布时间】:2013-09-02 14:09:01
【问题描述】:

我似乎正在为这段代码苦苦挣扎,如果有人能提供帮助,我们将不胜感激。

我在 web.config 文件中有一个数据字符串,格式如下:1、3、5、7、9、11、15、17、19。

我需要将数据传递到:private static readonly byte[] Entropy,但我不断收到错误消息:数据无效

如果我使用以下内容:

private static readonly byte[] Entropy = { 1, 3, 5, 7, 9, 11, 15, 17, 19}; 它工作正常,所以我的问题似乎是转换字符串转换成字节[]。

我在很多网站上搜索过这个问题(以下是一些)

C# convert string into its byte[] equivalent

http://social.msdn.microsoft.com/Forums/vstudio/en-US/08e4553e-690e-458a-87a4-9762d8d405a6/how-to-convert-the-string-to-byte-in-c-

Converting string to byte array in C#

http://www.chilkatsoft.com/faq/dotnetstrtobytes.html

但似乎没有任何效果。

如上所述,任何帮助将不胜感激。

private static readonly string WKey = ConfigurationManager.AppSettings["Entropy"];

        private static readonly byte[] Entropy = WKey; 

        public static string DecryptDataUsingDpapi(string encryptedData)
        { 
            byte[] dataToDecrypt    = Convert.FromBase64String(encryptedData);
            byte[] originalData     = ProtectedData.Unprotect(dataToDecrypt, Entropy, DataProtectionScope.CurrentUser); 
            return Encoding.Unicode.GetString(originalData);
        }

乔治

【问题讨论】:

    标签: c# security cryptography


    【解决方案1】:

    你可以:

    string Entropy = "1, 3, 5, 7, 9, 11, 15, 17, 19";
    var parts = Entropy.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    byte[] bytes = Array.ConvertAll(parts, p => byte.Parse(p));
    

    byte.Parse 将“吃掉”并忽略空格。请注意,您不能使用十六进制数字(AB,但没有0x,所以没有0xAB)。你需要:

    byte[] bytes = Array.ConvertAll(parts, p => byte.Parse(p, NumberStyles.HexNumber));
    

    但它不会接受非十六进制数字:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 2012-03-24
      • 2013-01-17
      • 2015-09-04
      • 1970-01-01
      • 1970-01-01
      • 2012-12-20
      相关资源
      最近更新 更多