我已经使用 OpenSSL 库来加密密码。我能够使用代码中的库成功加密和解密密码。
但是,如果我尝试在终端上的 linux 系统上解密库生成的密码,则解密失败。
加密:
openssl enc -aes-256-cbc -base64 -salt -k <passphrase> -in plain.txt -out
encrypt.txt
解密:
openssl enc -aes-256-cbc -base64 -salt -d -k <passphrase> -in encrypt.txt -out plain.txt
请帮忙。
我已经去除了盐,以使过程更简单。我在终端上生成了示例 base64 密码并尝试使用库解密,但失败了。我尝试使用 Library 生成示例 base64 密码并尝试在终端中解密它,这也失败了!
size_t init_key_iv(const std::string& pass, const unsigned char* salt, unsigned char* key, unsigned char* iv ) {
size_t derived_key_size = 0;
const unsigned char * pass_key = reinterpret_cast<const unsigned char*>( pass.c_str() );
const size_t pass_key_len = pass.size();
if(salt && key && iv && pass_key && pass_key_len > 0) {
memset(key, 0, sizeof(key));
memset( iv, 0, sizeof(iv));
derived_key_size = EVP_BytesToKey(cipher_type, msg_digest_type, salt, pass_key, pass_key_len, 5, key, iv);
}
return derived_key_size;
}
void encrypt(const unsigned char* msg, unsigned char** encrypted_message, const size_t msg_len, const unsigned char *key, unsigned char *iv) {
AES_KEY enc_key;
AES_set_encrypt_key(key, 256, &enc_key);
AES_cbc_encrypt(msg, *encrypted_message, msg_len, &enc_key, iv, AES_ENCRYPT);
}
void decrypt(const unsigned char* cipher, unsigned char** decrypted_msg, const size_t cipher_len, const unsigned char *key, unsigned char *iv ) {
AES_KEY enc_key;
AES_set_decrypt_key(key, 256, &enc_key);
AES_cbc_encrypt(cipher, *decrypted_msg, cipher_len, &enc_key, iv, AES_DECRYPT);
}
int decode(const char* b64_msg, unsigned char** decode_msg, const size_t decode_msg_len) {
size_t bytes_decoded = 0;
bytes_decoded = EVP_DecodeBlock(*decode_msg, (unsigned char *)b64_msg, strlen(b64_msg));
return bytes_decoded;
}
int encode(const unsigned char* msg, const size_t msg_len, char** b64_msg) {
size_t bytes_encoded = 0;
if(msg && msg_len > 0 && b64_msg) {
bytes_encoded = EVP_EncodeBlock((unsigned char *) *b64_msg, msg, msg_len);
}
return bytes_encoded;
}
const int derived_key_size = init_key_iv(password, salt, key, iv_enc);
encrypt((unsigned char *)msg, &encrypted_message, strlen(msg), key, iv_enc);
const size_t bytes_encoded( encode((const unsigned char*)encrypted_message, strlen(reinterpret_cast<char*>(encrypted_message)), &base64_enc_str) );
const size_t bytes_decoded( CBase64::decode(cipher_base64, &cipher, cipher_len) );
decrypt(cipher, &decrypted_message, cipher_len, key, iv_dec);
期望是;库生成的 base64 密码应在 openssl 终端中解密,反之亦然。