C++ 和 Qt 5 中的 AES 256 加密

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21885140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:51:54  来源:igfitidea点击:

AES 256 encryption in C++ and Qt 5

c++qtencryptionaes

提问by Parth Doshi

I have a Java code for encryption in place as follows!

我有一个用于加密的 Java 代码,如下所示!

private static byte[] encrypt(byte[] raw, byte[] clear) throws 
   Exception {  
    SecretKeySpec skeySpec = new SecretKeySpec(raw,  "AES");  
    Cipher cipher = null;

    if(isIVUsedForCrypto) {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(IV));  
    }
    else 
    {
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);  
    }
    byte[] encrypted = cipher.doFinal(clear);  
    return encrypted;  
}  

 public static byte[] toByte(String hexString) { 

    int len = hexString.length()/2;  
    byte[] result = new byte[len];  
    try{
    for (int i = 0; i < len; i++) { 
        result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2),16).byteValue();  
    }
    }catch (Exception e) {

    }
    return result;  
}  

public static String toHex(byte[] buf) {  
    if (buf == null)  
        return "";  
    StringBuffer result = new StringBuffer(2*buf.length);  
    for (int i = 0; i < buf.length; i++) {  
        appendHex(result, buf[i]);  
    }  
    return result.toString();  
}  
private final static String HEX = "0123456789ABCDEF";  
private static void appendHex(StringBuffer sb, byte b) {  
    sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));  
}  

From Java main method:

从Java主要方法:

  byte[] result = encrypt(toByte(rawKey), plaintext.getBytes());

I need to write the C++ equivalent for the above methods (in java). I am not aware of the C++ classes for Cryptography and would like someone to please provide an example showing the same.

我需要为上述方法编写 C++ 等价物(在 Java 中)。我不知道密码学的 C++ 类,希望有人提供一个示例来显示相同​​的内容。

Thanks in advance

提前致谢

EDIT

编辑

My raw key would be in hexadecimal like -> 729308A8E815F6A46EB3A8AE6D5463CA7B64A0E2E11BC26A68106FC7697E727E

我的原始密钥将是十六进制的 -> 729308A8E815F6A46EB3A8AE6D5463CA7B64A0E2E11BC26A68106FC7697E727E

and my final encrypted password is --> 812DCE870D82E93DB62CDA66AAF37FB2

我最终的加密密码是 --> 812DCE870D82E93DB62CDA66AAF37FB2

This works in Java but I need a similar solution for C++

这适用于 Java,但我需要一个类似的 C++ 解决方案

回答by sorush-r

Try this:

尝试这个:

#include <crypto++/aes.h>
#include <crypto++/modes.h>
#include <crypto++/filters.h>
#include <crypto++/hex.h>
#include <crypto++/sha.h>
#include <crypto++/md5.h>

QString Foo::decrypt(const QString &password)
{
    string plain;
    string encrypted = password.toStdString();
    // Hex decode symmetric key:
    HexDecoder decoder;
    decoder.Put( (byte *)PRIVATE_KEY,32*2 );
    decoder.MessageEnd();
    word64 size = decoder.MaxRetrievable();
    char *decodedKey = new char[size];
    decoder.Get((byte *)decodedKey, size);
    // Generate Cipher, Key, and CBC
    byte key[ AES::MAX_KEYLENGTH ], iv[ AES::BLOCKSIZE ];
    StringSource( reinterpret_cast<const char *>(decodedKey), true,
                  new HashFilter(*(new SHA256), new ArraySink(key, AES::MAX_KEYLENGTH)) );
    memset( iv, 0x00, AES::BLOCKSIZE );
    try {
        CBC_Mode<AES>::Decryption Decryptor
        ( key, sizeof(key), iv );
        StringSource( encrypted, true,
                      new HexDecoder(new StreamTransformationFilter( Decryptor,
                                     new StringSink( plain ) ) ) );
    }
    catch (Exception &e) { // ...
    }
    catch (...) { // ...
    }
    return QString::fromStdString(plain);
}

QString Foo::encrypt(const QString &password)
{
    string plain = password.toStdString();
    string ciphertext;
    // Hex decode symmetric key:
    HexDecoder decoder;
    decoder.Put( (byte *)PRIVATE_KEY, 32*2 );
    decoder.MessageEnd();
    word64 size = decoder.MaxRetrievable();
    char *decodedKey = new char[size];
    decoder.Get((byte *)decodedKey, size);
    // Generate Cipher, Key, and CBC
    byte key[ AES::MAX_KEYLENGTH ], iv[ AES::BLOCKSIZE ];
    StringSource( reinterpret_cast<const char *>(decodedKey), true,
                  new HashFilter(*(new SHA256), new ArraySink(key, AES::MAX_KEYLENGTH)) );
    memset( iv, 0x00, AES::BLOCKSIZE );
    CBC_Mode<AES>::Encryption Encryptor( key, sizeof(key), iv );
    StringSource( plain, true, new StreamTransformationFilter( Encryptor,
                  new HexEncoder(new StringSink( ciphertext ) ) ) );
    return QString::fromStdString(ciphertext);
}

Update:

更新:

Use above code as follows:

使用上面的代码如下:

//...
#define PRIVATE_KEY "729308A8E815F6A46EB3A8AE6D5463CA7B64A0E2E11BC26A68106FC7697E727E37011"
QString encrypted = Foo::encryptPassword("test");
// use encrypted

Personally I don't like to reveal private key in source code. So I'll pass it to compiler in command line:

我个人不喜欢在源代码中透露私钥。所以我会在命令行中将它传递给编译器:

g++ -DPRIVATE_KEY \"\"\"123...\"\"\" ...

Where PRIVATE_KEY is your private key in plain text. If you have the key in HEX encode, just remove Hex decode symmetric keystep.

其中 PRIVATE_KEY 是纯文本形式的私钥。如果您有十六进制编码的密钥,只需删除Hex decode symmetric key步骤。