rust 如何在给定rsa公钥的情况下创建加密的装甲文件

mspsb9vt  于 2023-03-18  发布在  其他
关注(0)|答案(2)|浏览(132)

我有一个字符串,我需要加密到ascii装甲与公钥,我有作为ascii装甲。
使用gpg的步骤是:

gpg --import <(echo '
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: PGP Command Line v10.4.2 (Build 1254) (Linux)

key data here
-----END PGP PUBLIC KEY BLOCK-----')

gpg -r identity-of-above@pubkey --armor -e file-of-string-to-encrypt

但是我需要在一个不依赖于GPG的程序中做到这一点,感觉X1 E0 F1 X和/或X1 E1 F1 X应该是我所寻求的,但是我甚至不能弄清楚如何从字符串中加载密钥。
如何加载密钥,然后使用rust生成一个加密文件?这是我到目前为止所写的:

use indoc::indoc;
use rsa::{pkcs1::DecodeRsaPublicKey, PaddingScheme, PublicKey, RsaPublicKey};

fn main() {
    let pem = indoc! {"
        -----BEGIN PGP PUBLIC KEY BLOCK-----
        Version: PGP Command Line v10.4.2 (Build 1254) (Linux)

        key data here
        -----END PGP PUBLIC KEY BLOCK-----
    "};
    let pub_key = RsaPublicKey::from_pkcs1_pem(&pem).unwrap();
    let data = b"contents I want to encrypt";
    let mut rng = rand::thread_rng();
    let enc_data = pub_key
        .encrypt(&mut rng, PaddingScheme::new_pkcs1v15_encrypt(), &data[..])
        .expect("failed to encrypt");
}

但是我得到了这个编译错误:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Asn1(Error { kind: Pem(HeaderDisallowed), position: None })', src/main.rs:51:54
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

很公平,但是我找不到如何为我的密钥类型做同样的密钥加载过程。我如何加载这个密钥?

voj3qocg

voj3qocg1#

在Rust Discord服务器上的一些人的帮助下,我确实设法对这个问题进行了排序。它需要使用MessageSignedPublicKeyDeserializable trait

use indoc::indoc;
use pgp::composed::message::Message;
use pgp::composed::signed_key::public::SignedPublicKey;
use pgp::composed::Deserializable;
use pgp::crypto::sym::SymmetricKeyAlgorithm;
use std::fs::File;

fn main() {
    let pem = indoc! {"
        -----BEGIN PGP PUBLIC KEY BLOCK-----
        Version: PGP Command Line v10.4.2 (Build 1254) (Linux)

        key data here
        -----END PGP PUBLIC KEY BLOCK-----
    "};
    let pub_key = SignedPublicKey::from_string(&pem).unwrap().0;
    assert!(pub_key.verify().is_ok());
    let data = "contents I want to encrypt";
    let fname = "encdata";
    let mut rng = rand::thread_rng();
    let mut file = File::create(fname).unwrap();
    let msg = Message::new_literal(&fname, &data)
        .encrypt_to_keys(&mut rng, SymmetricKeyAlgorithm::AES128, &[&pub_key])
        .unwrap()
        .to_armored_writer(&mut file, None);
}
pw136qt2

pw136qt22#

我也遇到过同样的问题,通过删除indoc!“和“}”之间每行前面的制表符来修复它

fn main() {
        ...
        let pem = indoc! {"
        -----BEGIN PGP PUBLIC KEY BLOCK-----
        Version: PGP Command Line v10.4.2 (Build 1254) (Linux)

        key data here
        -----END PGP PUBLIC KEY BLOCK-----
        "};
        ...
    }

相关问题