Skip to content

Instantly share code, notes, and snippets.

@AFutureD
Last active April 12, 2023 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AFutureD/307faca1237d6b1175fd647e1371c916 to your computer and use it in GitHub Desktop.
Save AFutureD/307faca1237d6b1175fd647e1371c916 to your computer and use it in GitHub Desktop.
A example about how to use AES algorithm for ring.
# ring = "0.16.20"
use ring::*;
use ring::aead::{Aad, AES_128_GCM, BoundKey, Nonce, OpeningKey, SealingKey, UnboundKey};
static ALGORITHM: &aead::Algorithm = &AES_128_GCM;
struct OneNonceSequence(Option<aead::Nonce>);
impl OneNonceSequence {
fn new(nonce: aead::Nonce) -> Self {
Self(Some(nonce))
}
}
impl aead::NonceSequence for OneNonceSequence {
fn advance(&mut self) -> Result<aead::Nonce, error::Unspecified> {
self.0.take().ok_or(error::Unspecified)
}
}
pub fn encrypt(content: String, key: String) -> Vec<u8>{
let unbound = UnboundKey::new(ALGORITHM, &key.as_bytes()[..ALGORITHM.key_len()]).unwrap();
let nonce_bytes = &key.as_bytes()[..ALGORITHM.nonce_len()];
let nonce = Nonce::assume_unique_for_key(<[u8; 12]>::try_from(nonce_bytes).unwrap());
let nonce_sequence = OneNonceSequence::new(nonce);
let mut sealing_key = SealingKey::new(unbound, nonce_sequence);
let aad = Aad::from(&[]);
let mut in_out = Vec::from(content);
sealing_key.seal_in_place_append_tag(aad, &mut in_out).unwrap();
in_out
}
pub fn decrypt(message: Vec<u8>, key: String) -> String {
let unbound = UnboundKey::new(ALGORITHM, &key.as_bytes()[..ALGORITHM.key_len()]).unwrap();
let nonce_bytes = &key.as_bytes()[..ALGORITHM.nonce_len()];
let nonce = Nonce::assume_unique_for_key(<[u8; 12]>::try_from(nonce_bytes).unwrap());
let nonce_sequence = OneNonceSequence::new(nonce);
let mut opening_key = OpeningKey::new(unbound, nonce_sequence);
let aad = Aad::from(&[]);
let mut in_out = message;
let decrypted = opening_key.open_in_place(aad, &mut in_out).unwrap();
String::from_utf8(decrypted.to_vec()).unwrap()
}
#[cfg(test)]
mod test {
use crate::utils::{decrypt, encrypt};
#[test]
fn it_works() {
let cnt = "hello world".to_string();
let key = "1234567890123456".to_string();
let vec = encrypt(cnt.clone(), key.clone());
let msg = decrypt(vec, key.clone());
println!("{}", msg);
assert_eq!(msg, cnt);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment