【问题标题】:How do I encrypt a string with an RSA public key from a ASN.1 x509 Byte array?如何使用 ASN.1 x509 字节数组中的 RSA 公钥加密字符串?
【发布时间】:2013-03-11 19:41:23
【问题描述】:

我有一个 ASN.1 x509 字节数组,其中包含 RSA 对的模数和公钥。我的目标是尽一切可能使用它来加密字符串。我正在尝试在objective-c中使用openssl来实现这一点。每当我尝试使用 d2i_X509 获取 RSA 对象时,它都会返回 null。如果我无法使用 openssl 完成此操作,我愿意切换到不同的库。请帮我找到有用的东西。

【问题讨论】:

  • 您是否确定要使用 RSA 密钥对加密/解密,而不是使用对称会话密钥(这是由您的 RSA 密钥对加密的实际内容;不是基础数据。这就是会话密钥的用途)?只是好奇。
  • 我确定。我得到了这个并且需要使用它

标签: objective-c c openssl x509 asn.1


【解决方案1】:

您通常不会直接使用 X.509 的公钥加密字符串。相反,您将生成一个强随机(特定质量)密钥;使用正常的对称加密(例如 AES),然后用它加密字符串。然后,您使用 X.509 加密随机密钥。

请参阅一本好的 PKI/加密书籍(例如 http://www.amazon.com/Applied-Cryptography-Protocols-Algorithms-Source/dp/0471117099)了解原因(关于密钥泄漏、位翻转、填充和(重新)加密两次的部分)。

如果您真的坚持要这样做,请查看 https://github.com/dirkx/smime-add-encryption-for-recipient/blob/master/smime-add-encrypt/main.c 它的 pkcs7_encode_rinfo 函数。

x509cert = ... something to read your x509 byte array in.

unsigned char *stuff = "Some zecret string";
int stufflen = strlen(stuff);

EVP_PKEY *pkey;
EVP_PKEY_CTX *pctx = NULL;

assert(pkey =  = X509_get_pubkey( x509cert));
assert(pctx = EVP_PKEY_CTX_new(pkey, NULL));
assert(EVP_PKEY_encrypt_init(pctx)==1);
assert((EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_ENCRYPT
                      EVP_PKEY_CTRL_PKCS7_ENCRYPT, 0, ri)==1);

size_t eklen;
assert(EVP_PKEY_encrypt(pctx, NULL, &eklen, stuff, stufflen)==1);

ek = OPENSSL_malloc(eklen);
assert(ek);

unsigned char *ek = NULL;
assert((EVP_PKEY_encrypt(pctx, ek, &eklen, key, keylen)==1);

printf("Encrypted blurp: ");
for(int i = 0; i < eklen; i++) {
    printf("0x%02X ", ek[i];
};
printf("\n");
exit(0);

【讨论】:

    猜你喜欢
    • 2014-10-29
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2021-03-30
    • 2018-05-02
    • 1970-01-01
    • 2021-02-21
    相关资源
    最近更新 更多