Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand DataProtection sample to illustrate buffer byte access #1626

Merged
merged 3 commits into from
Mar 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ bin
*.lock
*.user
*.filters
*.bin
1 change: 1 addition & 0 deletions crates/samples/data_protection/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ features = [
"Foundation",
"Storage_Streams",
"Security_Cryptography_DataProtection",
"Win32_System_WinRT",
]
20 changes: 14 additions & 6 deletions crates/samples/data_protection/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
use windows::{core::*, Security::Cryptography::DataProtection::*, Security::Cryptography::*};
use windows::{core::*, Security::Cryptography::DataProtection::*, Security::Cryptography::*, Storage::Streams::*, Win32::System::WinRT::*};

fn main() -> Result<()> {
fn main() -> std::io::Result<()> {
let provider = DataProtectionProvider::CreateOverloadExplicit("LOCAL=user")?;
let unprotected = CryptographicBuffer::ConvertStringToBinary("Hello world", BinaryStringEncoding::Utf8)?;

let buffer = CryptographicBuffer::ConvertStringToBinary("Hello world", BinaryStringEncoding::Utf8)?;

let protected = provider.ProtectAsync(buffer)?.get()?;
let protected = provider.ProtectAsync(unprotected)?.get()?;
let protected_bytes = unsafe { as_mut_bytes(&protected)? };
std::fs::write("secret.bin", protected_bytes)?;

let protected_bytes = std::fs::read("secret.bin")?;
let protected = CryptographicBuffer::CreateFromByteArray(&protected_bytes)?;
let unprotected = provider.UnprotectAsync(protected)?.get()?;

let message = CryptographicBuffer::ConvertBinaryToString(BinaryStringEncoding::Utf8, unprotected)?;

println!("{}", message);
Ok(())
}

unsafe fn as_mut_bytes(buffer: &IBuffer) -> Result<&mut [u8]> {
let interop = buffer.cast::<IBufferByteAccess>()?;
let data = interop.Buffer()?;
Ok(std::slice::from_raw_parts_mut(data, buffer.Length()? as _))
}