V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
RedBeanIce
V2EX  ›  Rust

rust 写代码真的很复杂

  •  
  •   RedBeanIce · 60 天前 · 2451 次点击
    这是一个创建于 60 天前的主题,其中的信息可能已经有所发展或是发生改变。
    ```rust
    use aes_gcm::{aead::{Aead, AeadCore, KeyInit, OsRng}, Aes256Gcm, AesGcm};
    use aes_gcm::aead::consts::U12;
    use aes_gcm::aead::Nonce;
    use aes_gcm::aes::Aes256;

    // aes-gcm = "0.10.3"

    #[test]
    fn test_3_aes256_cbc() {
    // 生成一个随机的 AES256-GCM 加密密钥 key 。
    // The encryption key can be generated randomly:
    let key = Aes256Gcm::generate_key(OsRng);

    // 使用生成的密钥 key 创建 AES256-GCM 加密器 cipher ,然后生成一个 96 位长度的随机 nonce nonce 。
    // 使用 cipher 对 "plaintext message" 进行加密得到 ciphertext ,然后再对 ciphertext 进行解密得到 plaintext 。
    // 最后使用 assert_eq! 宏来验证解密后的 plaintext 是否与原始消息相同。
    let cipher: AesGcm<Aes256, U12> = Aes256Gcm::new(&key);
    // 生成随机 nonce ( 96 bits )
    // let nonce = GenericArray::from_slice(&Aes256Gcm::generate_nonce(&mut OsRng));
    // let nonce: &GenericArray<u8, <Aes256Gcm as Aead>::NonceSize> = GenericArray::from_slice(&Aes256Gcm::generate_nonce(&mut OsRng));
    // let nonce: GenericArray<u8, <Aes256Gcm as Aead>::NonceSize> = ...;
    let nonce: Nonce<Aes256Gcm> = Aes256Gcm::generate_nonce(&mut OsRng); // 96-bits; unique per message

    // 将明文消息作为字节数组传递给 encrypt 函数。
    let plaintext: &[u8] = b"plaintext message";
    let ciphertext = cipher.encrypt(&nonce, plaintext).unwrap();
    let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref()).unwrap();

    assert_eq!(&plaintext, b"plaintext message");
    }


    ```

    let plaintext: &[u8] = b"plaintext message";

    这一行代码,要自己将手动推导的 &[u8;17] 固定长度数组,,修改为可变数组。。

    以及一些其他的,,整个代码才可以运行
    5 条回复    2024-07-30 11:43:45 +08:00
    chainal7777
        1
    chainal7777  
       60 天前
    1 ,用点 use as
    2 ,用点 type A=a
    3 ,只写关键注释
    RedBeanIce
        2
    RedBeanIce  
    OP
       60 天前
    @chainal7777 请问第一点是什么意思呀,,,,‘’第二点我大概理解,就是将泛型定义变成单独的一行代码。
    cppc
        3
    cppc  
       60 天前 via iPhone
    为了安全是这样啦,我还见过编译时 SQL 检查呢,SQL 写错代码都不能编译
    PTLin
        4
    PTLin  
       59 天前
    不是 rust 复杂,这个是库复杂,用了太多泛型了
    whoami9894
        5
    whoami9894  
       39 天前
    有没有可能,不用写那么多类型标注

    另外,函数当然不可能接收 [u8; const N] 参数,难道你能在编译期知道数据长度?

    ```
    let key = Aes256Gcm::generate_key(OsRng);
    let cipher = Aes256Gcm::new(&key);
    let nonce = Aes256Gcm::generate_nonce(OsRng);

    let plaintext = b"plaintext message";
    let ciphertext = cipher.encrypt(&nonce, plaintext.as_slice()).unwrap();
    let plaintext = cipher.decrypt(&nonce, ciphertext.as_slice()).unwrap();

    assert_eq!(&plaintext, b"plaintext message");
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2428 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:13 · PVG 08:13 · LAX 17:13 · JFK 20:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.