diff --git a/.gitignore b/.gitignore index 84928cdc41..69682a318c 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ bin *.lock *.user *.filters +*.bin diff --git a/crates/samples/data_protection/Cargo.toml b/crates/samples/data_protection/Cargo.toml index 70feccec8f..40acfa6ca0 100644 --- a/crates/samples/data_protection/Cargo.toml +++ b/crates/samples/data_protection/Cargo.toml @@ -10,4 +10,5 @@ features = [ "Foundation", "Storage_Streams", "Security_Cryptography_DataProtection", + "Win32_System_WinRT", ] diff --git a/crates/samples/data_protection/src/main.rs b/crates/samples/data_protection/src/main.rs index dcf712cb37..17f3a85ddb 100644 --- a/crates/samples/data_protection/src/main.rs +++ b/crates/samples/data_protection/src/main.rs @@ -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::()?; + let data = interop.Buffer()?; + Ok(std::slice::from_raw_parts_mut(data, buffer.Length()? as _)) +}