解密使用包含空值的密码加密的私钥

时间:2016-10-07 07:01:02

标签: c openssl

我有以下(非常简化的)代码,它使用OpenSSL生成加密的私钥,使用包含null作为密码的字符串:

#include <stdio.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
int main(int argc, char *argv[]) {
    char password[32] = "pass\000word";
    extern FILE *stdout;
    EVP_PKEY *key = NULL;
    RSA *rsa;

    SSL_library_init();
    OpenSSL_add_all_algorithms();

    rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL);
    key = EVP_PKEY_new();

    EVP_PKEY_assign(key, EVP_PKEY_RSA, rsa);

    /* Write the private key to the file */
    PEM_write_PrivateKey(stdout, key, EVP_des_ede3_cbc(), (unsigned char*)password, 32, NULL, NULL);
    return 0;
}

加密的私钥是按预期创建的,但我无法使用PEM_read_PrivateKey(3ssl)以编程方式解密,也无法使用openssl pkcs8 -in key.pam -passin file:key.pass从命令行解密。

$ od -ta key.pass
0000000   p   a   s   s nul   w   o   r   d nul nul nul nul nul nul nul
0000020 nul nul nul nul nul nul nul nul nul nul nul nul nul nul nul nul
0000040

从我所看到的情况来看,与PEM_read_PrivateKey不同,null只接受PEM_write_PrivateKey终止的密码短语。

如何解密生成的密钥?

1 个答案:

答案 0 :(得分:2)

使用来电者提供的回叫来执行密码配置。以下是完全蛮力,丑陋,没有错误检查,绝不是我的编码习惯的示例,但演示了我所指的:

def get_character("compressed_string",index)
  expanded_string = calculate_expanded_string(compressed_string)
  required_char = expanded_string(char_at, index_number(for eg 3))
end

def calculate_expanded_string(compressed_string)
  return expanded
end

它应该将加密密钥转储到#include <stdio.h> #include <string.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/pem.h> int password_cb (char *buf, int size, int rwflag, void *userdata) { memcpy(buf, userdata, 32); return 32; } int main(int argc, char *argv[]) { char password[32] = "pass\0word"; EVP_PKEY *key = NULL; RSA *rsa; OpenSSL_add_all_algorithms(); rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL); key = EVP_PKEY_new(); EVP_PKEY_assign(key, EVP_PKEY_RSA, rsa); /* Write the private key to the file */ FILE *fp = fopen("somekey.pem", "w"); PEM_write_PrivateKey(fp, key, EVP_aes_128_cbc(), (unsigned char*)password, sizeof(password), NULL, NULL); fclose(fp); EVP_PKEY* rdkey = NULL; fp = fopen("somekey.pem", "r"); PEM_read_PrivateKey(fp, &rdkey, password_cb, password); fclose(fp); PEM_write_PrivateKey(stdout, key, NULL, NULL, 0, NULL, NULL); PEM_write_PrivateKey(stdout, rdkey, NULL, NULL, 0, NULL, NULL); return 0; } ,使用相同的密码从somekey.pem读取加密密钥,最后将两个密钥转储到stdout。这两个明文标准键最好是相同的......它们是:

示例输出

somekey.pem

希望这就是你要找的东西。