SecureString 到 Byte[] C#

swift

1个回答

写回答

578168690

2025-06-24 04:05

+ 关注

AI
AI

在C#中,我们经常需要处理敏感数据,例如密码、密钥等。为了确保这些敏感数据的安全性,我们可以使用SecureString类来存储它们。SecureString类是.NET框架提供的一种加密字符串的方式,它能够在内存中加密存储字符串数据,以防止被恶意访问。

使用SecureString类将字符串转换为字节数组是一种常见的操作。这通常是为了在存储或传输数据时,将SecureString对象转换为字节数组以便于处理。在下面的示例中,我们将演示如何将SecureString对象转换为字节数组。

首先,我们需要创建一个SecureString对象,并向其添加敏感数据。在本例中,我们将使用密码作为示例数据。

csharp

using System;

using System.Runtime.InteropServices;

using System.Security;

public class Example

{

public static void MAIn()

{

// 创建一个SecureString对象

SecureString secureString = new SecureString();

// 向SecureString对象添加敏感数据

Console.WriteLine("请输入密码:");

ConsoleKeyInfo key;

do

{

key = Console.ReadKey(true);

// 将按键字符添加到SecureString对象中

if (key.Key != ConsoleKey.Enter)

{

secureString.AppendChar(key.KeyChar);

Console.Write("*");

}

} while (key.Key != ConsoleKey.Enter);

// 转换SecureString对象为字节数组

byte[] byteArray = ConvertSecureStringToByteArray(secureString);

// 打印字节数组的内容

Console.WriteLine("\nSecureString转换为字节数组的结果:");

foreach (byte b in byteArray)

{

Console.Write($"{b:X2} ");

}

Console.WriteLine();

}

// 将SecureString对象转换为字节数组

public static byte[] ConvertSecureStringToByteArray(SecureString secureString)

{

byte[] byteArray = new byte[secureString.Length * 2];

IntPtr ptr = IntPtr.Zero;

try

{

// 将SecureString对象的内容复制到一个指针中

ptr = Marshal.SecureStringToGlobalAllocUnicode(secureString);

// 将指针中的数据复制到字节数组中

Marshal.Copy(ptr, byteArray, 0, byteArray.Length);

}

finally

{

// 清除指针中的数据

Marshal.ZeroFreeGlobalAllocUnicode(ptr);

}

return byteArray;

}

}

在上面的代码中,我们首先创建了一个SecureString对象,并使用Console.ReadKey方法读取用户输入的密码字符。然后,我们将输入的字符添加到SecureString对象中,同时在控制台上显示"*"代替输入的字符。接下来,我们调用ConvertSecureStringToByteArray方法将SecureString对象转换为字节数组。在该方法中,我们使用Marshal.SecureStringToGlobalAllocUnicode方法将SecureString对象的内容复制到一个指针中,然后使用Marshal.Copy方法将指针中的数据复制到字节数组中。最后,我们打印字节数组的内容。

如何将SecureString转换为字节数组

在上面的示例中,我们展示了如何使用C#将SecureString对象转换为字节数组。这对于安全存储和传输敏感数据非常有用。通过使用SecureString类,我们可以确保敏感数据在内存中得到加密存储,提高了数据的安全性。

本文介绍了如何在C#中使用SecureString类将字符串转换为字节数组。通过使用SecureString类,我们可以更安全地处理敏感数据,保护用户的密码、密钥等重要信息。希望本文对您有所帮助!

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号