From f7605dfefa304b1a7b20a474ce168cd5b9849533 Mon Sep 17 00:00:00 2001
From: stuebinm
Date: Sun, 4 Apr 2021 15:25:24 +0200
Subject: age-wasm: add a function for asymmetric decryption

This is intended for misusing an age private key as "passphrase" for
decrypting a document. This is not really recommended, but it is useful,
since symmetric encryption in web assembly takes some orders of magnitude
(1-2 minutes) longer than asymmetric decryption.
---
 age-wasm/src/lib.rs | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)

(limited to 'age-wasm/src')

diff --git a/age-wasm/src/lib.rs b/age-wasm/src/lib.rs
index 0f6fb67..fbf0b19 100644
--- a/age-wasm/src/lib.rs
+++ b/age-wasm/src/lib.rs
@@ -3,8 +3,9 @@ mod utils;
 use wasm_bindgen::prelude::*;
 
 use std::io::{Read, Write};
+use std::iter;
 
-use age::x25519::Recipient;
+use age::x25519::{Recipient, Identity};
 
 //use rand::{rngs::OsRng, RngCore};
 
@@ -38,6 +39,24 @@ pub fn age_encrypt(plaintext: String, key: String) -> Option<Vec<u8>> {
     Some(encrypted)
 }
 
+#[wasm_bindgen]
+pub fn age_decrypt (blob: Vec<u8>, privkey: String) -> Option<String> {
+    utils::set_panic_hook();
+
+    let key = privkey.parse::<Identity>().ok()?;
+    let decryptor = match age::Decryptor::new(&blob[..]).ok()? {
+        age::Decryptor::Recipients(d) => d,
+        _ => panic!("something weird happend while trying to read the ciphertext"),
+    };
+
+    let mut decrypted = vec![];
+    let mut reader = decryptor.decrypt(
+        iter::once(Box::new(key) as Box<dyn age::Identity>)).ok()?;
+    reader.read_to_end(&mut decrypted).ok()?;
+
+    Some(std::str::from_utf8(&decrypted).ok()?.to_owned())
+}
+
 #[wasm_bindgen]
 pub fn age_decrypt_passphrase(blob: Vec<u8>, passphrase: String) -> Option<String> {
     utils::set_panic_hook();
-- 
cgit v1.2.3