Skip to content

Commit

Permalink
Expand DataProtection sample to illustrate buffer byte access (#1626)
Browse files Browse the repository at this point in the history
  • Loading branch information
kennykerr authored Mar 23, 2022
1 parent 38a0d2d commit c31774a
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
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 _))
}

0 comments on commit c31774a

Please sign in to comment.