Module openssl::md_ctx

source ·
Expand description

The message digest context.

Examples

Compute the SHA256 checksum of data

use openssl::md::Md;
use openssl::md_ctx::MdCtx;

let mut ctx = MdCtx::new().unwrap();
ctx.digest_init(Md::sha256()).unwrap();
ctx.digest_update(b"Some Crypto Text").unwrap();
let mut digest = [0; 32];
ctx.digest_final(&mut digest).unwrap();

assert_eq!(
    digest,
    *b"\x60\x78\x56\x38\x8a\xca\x5c\x51\x83\xc4\xd1\x4d\xc8\xf9\xcc\xf2\
       \xa5\x21\xb3\x10\x93\x72\xfa\xd6\x7c\x55\xf5\xc9\xe3\xd1\x83\x19",
);

Sign and verify data with RSA and SHA256

use openssl::md::Md;
use openssl::md_ctx::MdCtx;
use openssl::pkey::PKey;
use openssl::rsa::Rsa;

// Generate a random RSA key.
let key = Rsa::generate(4096).unwrap();
let key = PKey::from_rsa(key).unwrap();

let text = b"Some Crypto Text";

// Create the signature.
let mut ctx = MdCtx::new().unwrap();
ctx.digest_sign_init(Some(Md::sha256()), &key).unwrap();
ctx.digest_sign_update(text).unwrap();
let mut signature = vec![];
ctx.digest_sign_final_to_vec(&mut signature).unwrap();

// Verify the signature.
let mut ctx = MdCtx::new().unwrap();
ctx.digest_verify_init(Some(Md::sha256()), &key).unwrap();
ctx.digest_verify_update(text).unwrap();
let valid = ctx.digest_verify_final(&signature).unwrap();
assert!(valid);


Compute and verify an HMAC-SHA256

use openssl::md::Md;
use openssl::md_ctx::MdCtx;
use openssl::memcmp;
use openssl::pkey::PKey;

// Create a key with the HMAC secret.
let key = PKey::hmac(b"my secret").unwrap();

let text = b"Some Crypto Text";

// Compute the HMAC.
let mut ctx = MdCtx::new().unwrap();
ctx.digest_sign_init(Some(Md::sha256()), &key).unwrap();
ctx.digest_sign_update(text).unwrap();
let mut hmac = vec![];
ctx.digest_sign_final_to_vec(&mut hmac).unwrap();

// Verify the HMAC. You can't use MdCtx to do this; instead use a constant time equality check.
let valid = memcmp::eq(&hmac, &target);
assert!(valid);

Structs