SecureString usage

本文介绍了如何利用.NET 2.0中的SecureString类来安全地在内存中存储敏感信息,如密码或连接字符串等。文章详细阐述了通过逐字符设置SecureString值的方法,并提供了从SecureString中检索值的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Getting and Setting a SecureString in .NET 2.0

SecureString Class
A nice new addition to the .NET 2.0 Framework is the SecureString class making it safe to store sensitive information in memory (e.g. passwords, connection strings). This class takes care of encrypting this information but the class does not provide a very straightforward method for getting and setting its value.

Since the actual value of the string is NOT stored in the memory space of your process it is not really a "managed" value so a bit of marshaling is required to work with it.

Setting a SecureString's value
Fortunately, it is rather easy to set the value of a SecureString ... but it has to be character by character. I assume the reason for this is because you really should not be using any transient/temporary variable to load the data into the SecureString. That would pretty much defeat its purpose. However, there will come a time when you want to set the value of the SecureString FROM another string. That much is simple:

SecureString securePassword = new SecureString();
string insecurePassword = "password";

foreach(char passChar in insecurePassword.ToCharArray())
{
    securePassword.AppendChar(passChar);
}



The above code simply iterates through the characters in the string and appends them to the SecureString.

Getting a SecureString's value
It is as difficult, however, to retrieve the value from a SecureString as it was simple to set it. Since the value of the SecureString is not in the application's process space your code has to interact with it via a pointer to a BSTR:

IntPtr passwordBSTR = default(IntPtr);

try {
    passwordBSTR = Marshal.SecureStringToBSTR(securePassword);
    insecurePassword = Marshal.PtrToStringBSTR(passwordBSTR);
} catch {
    insecurePassword = "";
}


This code uses the Marshal static class to retrieve the value of the SecureString into a BTRS and returns its pointer. Next, again using the Marshal class to reads the BSTR into a managed string vairable to be used at will.

Is this secure?
No ... not really. It should be apparent by now that you are taking the value out of a secure, encrypted memory location and putting it right back into an insecure, unencrypted location.

 

(from http://jasondotnet.spaces.live.com/Blog/cns!BD40DBF53845E64F!148.entry)

咦 刚刚网页怎么崩了 我们说到 昨天你发我的架构:”E:\ProjectEcosystem\ ├── ProjectMonitor\ # 项目监控系统 │ ├── monitor.py │ ├── state_analyzer.py │ └── project_state.db │ ├── InnovationHub\ # 创新管理系统 │ ├── idea_capture.py │ ├── evaluator.py │ ├── roadmap_generator.py │ └── backlog\ # 想法存储目录 │ └── AI_Agents\ # 智能体项目(独立存在) ├── main_agent.py └── ... E:\ProjectEcosystem\ProjectMonitor\ ├── MyWebApp/ │ ├── src/ # 源代码目录 │ ├── docs/ # 文档目录 │ ├── tests/ # 测试代码 │ ├── config/ # 配置文件 │ ├── logs/ # 日志文件 │ ├── .gitignore # Git忽略规则 │ └── MyWebApp.code-workspace # VS Code工作区文件 E:\ProjectEcosystem\ └── ProjectMonitor/ ├── Initialize-DevEnv.ps1 # 项目初始化脚本 ├── Monitor-Project.ps1 # 项目监控脚本 ├── project_monitor.log # 监控日志 ├── EcoMonitor/ # 示例项目 ├── DataAnalysis/ # 另一个项目 └── ... # 更多项目 和我们的进度:”PS C:\Users\Administrator> PS C:\Users\Administrator> # 步骤1: 导航到项目目录 >> cd E:\ProjectEcosystem\ProjectMonitor >> >> # 步骤2: 创建新项目 >> .\Initialize-DevEnv.ps1 >> Initialize-Project -ProjectName "EcoMonitor" -ProjectType "node" >> >> # 步骤3: 启动项目监控 >> .\Monitor-Project.ps1 >> Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 E:\ProjectEcosystem\ProjectMonitor\Initialize-DevEnv.ps1:199 字符: 1 + Export-ModuleMember -Function Initialize-Project + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand Initialize-Project : 无法将“Initialize-Project”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写, 如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:6 字符: 1 + Initialize-Project -ProjectName "EcoMonitor" -ProjectType "node" + ~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Initialize-Project:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS E:\ProjectEcosystem\ProjectMonitor> .\Initialize-DevEnv.ps1 >> Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 E:\ProjectEcosystem\ProjectMonitor\Initialize-DevEnv.ps1:199 字符: 1 + Export-ModuleMember -Function Initialize-Project + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS E:\ProjectEcosystem\ProjectMonitor> code .\MyWebApp\MyWebApp.code-workspace >> PS E:\ProjectEcosystem\ProjectMonitor> # 在项目初始化函数中添加 >> function Initialize-Project { >> # ... 其他代码 ... >> >> # 创建信任锚文件 >> $trustAnchorDir = Join-Path $env:APPDATA "Code/User/WorkspaceStorage" >> $trustAnchorFile = Join-Path $trustAnchorDir "trusted-workspaces.json" >> >> if (-not (Test-Path $trustAnchorFile)) { >> New-Item -Path $trustAnchorFile -Force | Out-Null >> Set-Content $trustAnchorFile '{"$mid":1,"folders":{}}' >> } >> >> # 添加当前项目到信任列表 >> $trusted = Get-Content $trustAnchorFile | ConvertFrom-Json >> $projectHash = (Get-FileHash -Algorithm SHA256 -InputStream ([IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes($projectDir)))).Hash >> $trusted.folders | Add-Member -NotePropertyName $projectHash -NotePropertyValue @{ >> "trusted" = $true >> "uri" = [Uri]::new($projectDir).AbsoluteUri >> } -Force >> >> $trusted | ConvertTo-Json -Depth 10 | Set-Content $trustAnchorFile >> >> # ... 其他代码 ... >> } >> PS E:\ProjectEcosystem\ProjectMonitor> # 修改最后打开项目的命令 >> Write-Host "🛠 Open project in VS Code with:" -ForegroundColor Cyan >> Write-Host " code --trust '$ProjectName.code-workspace'" -ForegroundColor Yellow >> 🛠 Open project in VS Code with: code --trust '.code-workspace' PS E:\ProjectEcosystem\ProjectMonitor> # 打开项目时添加 --trust 参数 >> code --trust .\MyWebApp\MyWebApp.code-workspace >> Warning: 'trust' is not in the list of known options, but still passed to Electron/Chromium. PS E:\ProjectEcosystem\ProjectMonitor> %APPDATA%\Code\User\WorkspaceStorage\trusted-workspaces.json %APPDATA%\Code\User\WorkspaceStorage\trusted-workspaces.json : 无法加载模块“%APPDATA%”。有关详细信息,请运行“Import- Module %APPDATA%”。 所在位置 行:1 字符: 1 + %APPDATA%\Code\User\WorkspaceStorage\trusted-workspaces.json + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (%APPDATA%\Code\...workspaces.json:String) [], CommandNotFoundException + FullyQualifiedErrorId : CouldNotAutoLoadModule PS E:\ProjectEcosystem\ProjectMonitor> { >> "$mid": 1, >> "folders": { >> "SHA256_HASH_OF_PROJECT_PATH": { >> "trusted": true, >> "uri": "file:///path/to/project" >> } >> } >> } >> 所在位置 行:2 字符: 9 + "$mid": 1, + ~ 表达式或语句中包含意外的标记“:”。 所在位置 行:4 字符: 34 + "SHA256_HASH_OF_PROJECT_PATH": { + ~ 表达式或语句中包含意外的标记“:”。 所在位置 行:5 字符: 16 + "trusted": true, + ~ 表达式或语句中包含意外的标记“:”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken PS E:\ProjectEcosystem\ProjectMonitor> function Initialize-Project { >> param( >> [Parameter(Mandatory=$true)] >> [string]$ProjectName, >> >> [ValidateSet("web", "python", "node", "dotnet")] >> [string]$ProjectType = "web", >> >> [string]$RootPath = "E:\ProjectEcosystem\ProjectMonitor" >> ) >> >> # ... 项目创建代码 ... >> >> # 信任锚处理 >> $trustAnchorDir = Join-Path $env:APPDATA "Code/User/WorkspaceStorage" >> New-Item -ItemType Directory -Path $trustAnchorDir -Force | Out-Null >> $trustAnchorFile = Join-Path $trustAnchorDir "trusted-workspaces.json" >> >> # 创建或更新信任锚文件 >> $trusted = @{"`$mid"=1; "folders"=@{}} >> if (Test-Path $trustAnchorFile) { >> $trusted = Get-Content $trustAnchorFile | ConvertFrom-Json -AsHashtable >> } >> >> # 添加当前项目 >> $projectHash = (Get-FileHash -Algorithm SHA256 -InputStream ( >> [IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes($projectDir)) >> )).Hash >> >> $trusted.folders[$projectHash] = @{ >> "trusted" = $true >> "uri" = [Uri]::new($projectDir).AbsoluteUri >> } >> >> $trusted | ConvertTo-Json -Depth 10 | Set-Content $trustAnchorFile >> >> # 输出打开命令 >> Write-Host "✅ Project '$ProjectName' created at: $projectDir" -ForegroundColor Green >> Write-Host "🛠 Open project securely with:" -ForegroundColor Cyan >> Write-Host " code --trust '$ProjectName.code-workspace'" -ForegroundColor Yellow >> } >> PS E:\ProjectEcosystem\ProjectMonitor> # 为每个项目创建专用用户 >> $secureUser = "user_$ProjectName" >> New-LocalUser -Name $secureUser -Password (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force) >> Name Enabled Description ---- ------- ----------- user_ True PS E:\ProjectEcosystem\ProjectMonitor> # 限制项目资源访问 >> New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" ` >> -Name "DisableRestrictedAdmin" ` >> -Value 0 ` >> -PropertyType DWORD ` >> -Force >> DisableRestrictedAdmin : 0 PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control PSChildName : Lsa PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry PS E:\ProjectEcosystem\ProjectMonitor> # 添加自动安全扫描 >> Start-Job -ScriptBlock { >> & "C:\Program Files\Windows Defender\MpCmdRun.exe" -Scan -ScanType 3 -File $using:projectDir >> } >> Start-Job : 无法检索 using 变量 '$using:projectDir' 的值,因为未在本地会话中设置该变量。 所在位置 行:2 字符: 1 + Start-Job -ScriptBlock { + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Start-Job],RuntimeException + FullyQualifiedErrorId : UsingVariableIsUndefined,Microsoft.PowerShell.Commands.StartJobCommand PS E:\ProjectEcosystem\ProjectMonitor> cd .\MyWebApp >> git init >> git add . >> git commit -m "Initial commit" >> Initialized empty Git repository in E:/ProjectEcosystem/ProjectMonitor/MyWebApp/.git/ Author identity unknown *** Please tell me who you are. Run git config --global user.email "you@example.com" git config --global user.name "Your Name" to set your account's default identity. Omit --global to set the identity only in this repository. fatal: unable to auto-detect email address (got 'Administrator@BF-202503252000.(none)') PS E:\ProjectEcosystem\ProjectMonitor\MyWebApp> # 保存所有工作后执行: >> rundll32.exe powrprof.dll,SetSuspendState 0,1,0 >> PS E:\ProjectEcosystem\ProjectMonitor\MyWebApp>“ 我们现在应该干什么 “
08-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值