如何在Crypto ++中使用自定义键

时间:2014-12-07 12:20:11

标签: c++ encryption key crypto++ passphrase

我在这个问题中提到加密代码的问题: Crypto++ encrypt and decrypt in two different c++ programs

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

1 个答案:

答案 0 :(得分:1)

  

如果我想使用自定义键/ 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 ++提供了其中两个。第一个是Elliptic Curve Integrated Encryption Scheme,它在椭圆诅咒的领域上运作。第二个是Discrete Logarithm Integrated Encryption Scheme,它在整数字段上运行。

为什么“甚至更好”有很多不明显的原因,但最重要的原因是IND-CCA2。其他更实用的包括: 不能 重用安全上下文,因为系统内置了正确的用法;并且已经删除了填充,这大大简化了证明并避免了潜在的神谕。该系统也以Discrete Logs为基础,这使得它成为一个基于Diffie-Hellman的问题,而且它被认为在任何地方都很难。