繁体   English   中英

如何在Crypto ++中使用自定义密钥

[英]How to use a custom key in Crypto++

我有一个问题涉及此问题中的加密代码: Crypto ++在两个不同的c ++程序中进行加密和解密

如果我想使用自定义键/ iv,该怎么做?

如果我想使用自定义键/ iv,该怎么做?

只需将其插入具有模式的密码即可。 有很多模式可供选择,但是您应该使用经过身份验证的加密模式,例如EAX,CCM或GCM。 有关Crypto ++ 模式的讨论,请参见Category:Mode

下面的代码采用密码或机密,对密码进行加密,然后对消息进行加密和编码。 接下来,它对加密的消息进行解码。 最后,它输出一些参数。


try {

    // KDF parameters
    string password = "Super secret password";
    unsigned int iterations = 15000;
    char purpose = 0; // unused by Crypto++

    // 32 bytes of derived material. Used to key the cipher.
    //   16 bytes are for the key, and 16 bytes are for the iv.
    SecByteBlock derived(32);

    // KDF function
    PKCS5_PBKDF2_HMAC<SHA256> kdf;
    kdf.DeriveKey(derived.data(), derived.size(), purpose, (byte*)password.data(), password.size(), NULL, 0, iterations);

    // Encrypt a secret message
    string plaintext = "Attack at dawn", ciphertext, recovered;

    // Key the cipher
    EAX<AES>::Encryption encryptor;
    encryptor.SetKeyWithIV(derived.data(), 16, derived.data() + 16, 16);

    AuthenticatedEncryptionFilter ef(encryptor, new StringSink(ciphertext));
    ef.Put((byte*)plaintext.data(), plaintext.size());
    ef.MessageEnd();

    // Key the cipher
    EAX<AES>::Decryption decryptor;
    decryptor.SetKeyWithIV(derived.data(), 16, derived.data() + 16, 16);

    AuthenticatedDecryptionFilter df(decryptor, new StringSink(recovered));
    df.Put((byte*)ciphertext.data(), ciphertext.size());
    df.MessageEnd();

    // Done with encryption and decryption

    // Encode various parameters
    HexEncoder encoder;
    string key, iv, cipher;

    encoder.Detach(new StringSink(key));
    encoder.Put(derived.data(), 16);
    encoder.MessageEnd();

    encoder.Detach(new StringSink(iv));
    encoder.Put(derived.data() + 16, 16);
    encoder.MessageEnd();

    encoder.Detach(new StringSink(cipher));
    encoder.Put((byte*)ciphertext.data(), ciphertext.size());
    encoder.MessageEnd();

    // Print stuff
    cout << "plaintext: " << plaintext << endl;
    cout << "key: " << key << endl;
    cout << "iv: " << iv << endl;
    cout << "ciphertext: " << cipher << endl;
    cout << "recovered: " << recovered << endl;

}
catch(CryptoPP::Exception& ex)
{
    cerr << ex.what() << endl;
}

程序运行将产生以下输出。

$ ./cryptopp-test.exe
plaintext: Attack at dawn
key: 7A8C7732898FB687669CB7DBEFBDD789
iv: 0AA980BABE72797E415C9B8979BF30EF
ciphertext: 197D0BD1A12577393AD1B1696B75D0FC6B8A142CF15B5F887AA965CE75F0
recovered: Attack at dawn

更好的是,使用集成加密方案。 Crypto ++提供了其中两个。 第一个是椭圆曲线集成加密方案 ,该方案在椭圆形诅咒域上运行。 第二种是离散对数集成加密方案 ,该方案在整数字段上运行。

它的“更好”的原因有很多不明显的原因,但最大的原因是其IND-CCA2 其他更实际的方法包括:您不能重复使用安全上下文,因为正确的使用已内置在系统中; 和填充已被删除,这大大简化了证明,并避免了潜在的预言。 该系统还基于Discrete Logs ,这使它成为基于Diffie-Hellman的问题,并且在任何地方都很难解决。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM