将对象转换为字节[]

发布于 2024-10-12 05:44:26 字数 280 浏览 2 评论 0原文

我正在尝试将检索到的注册表值从 object 转换为 byte[]。它存储为REG_BINARY。我尝试将 BinaryFormatterMemoryStream 一起使用。但是,它添加了我不想要的开销信息。当我通过执行函数 Convert.ToBase64String(..) 将字节数组转换为字符串时,我观察到了这一点。我执行这些功能是因为我正在测试注册表中加密密钥的存储和检索。

I am trying to convert a retrieved registry value from object to byte[]. It is stored as REG_BINARY. I tried using BinaryFormatter with MemoryStream. However, it adds overhead information that I do not want. I observed this when I then converted the byte array to a string by performing the function Convert.ToBase64String(..). I am performing these functions because I am testing the storing and retrieval of an encrypted key in the registry.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心舞飞扬 2024-10-19 05:44:26

如果它是 REG_BINARY,那么当您检索它时,它应该已经是一个字节数组...难道您不能将其转换为 byte[] 吗?

或者,如果您尚未验证代码中的REG_BINARY,您可能需要使用:

byte[] binaryData = value as byte[];
if (binaryData == null)
{
    // Handle case where value wasn't found, or wasn't binary data
}
else
{
    // Use binaryData here
}

If it's a REG_BINARY then it should already be a byte array when you retrieve it... can't you just cast it to byte[]?

Alternatively, if you haven't already verified that it's REG_BINARY in the code, you may want to use:

byte[] binaryData = value as byte[];
if (binaryData == null)
{
    // Handle case where value wasn't found, or wasn't binary data
}
else
{
    // Use binaryData here
}
恍梦境° 2024-10-19 05:44:26

试试这个。如果它已经是 REG_BINARY,您需要做的就是转换它:

static byte[] GetFoo()
{

  var obj = Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\Software", "foo", null);
  //TODO: Write a better exception for when it isn't found
  if (obj == null) throw new Exception(); 

  var bytearray = obj as byte[];
  //TODO: Write a better exception for when its found but not a REG_BINARY
  if (bytearray == null) throw new Exception(); 

  return bytearray;
}

Try this. If it already is a REG_BINARY, all you need to do is cast it:

static byte[] GetFoo()
{

  var obj = Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\Software", "foo", null);
  //TODO: Write a better exception for when it isn't found
  if (obj == null) throw new Exception(); 

  var bytearray = obj as byte[];
  //TODO: Write a better exception for when its found but not a REG_BINARY
  if (bytearray == null) throw new Exception(); 

  return bytearray;
}
关于从前 2024-10-19 05:44:26

如果您使用 Convert.ToBase64String 转换它,您应该能够类似地得到它。

string regValueAsString = (string)regValueAsObj;
byte[] buf = Convert.FromBase64String(regValueAsString);

If you converted it using Convert.ToBase64String, you should be able to get it out similarly.

string regValueAsString = (string)regValueAsObj;
byte[] buf = Convert.FromBase64String(regValueAsString);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文