您可以将示例复制粘贴到http://wiki.openssl.org/index.php/EVP_Authenticated_Encryption_and_Decryption并进行一些更改。
首先,您需要对 SJCL 的数据进行 Base64 解码。但你知道的。
其次,您需要将消息拆分为 ct 和 tag。在这种情况下,ct 是前 9 个字节,tag 是从 ct[9] 开始的 8 个字节。
第三,需要将标签长度设置为ts/8 = 8,并且需要正确设置IV长度。如果您在 SJCL 中将 IV 设置得太长,它会将其截断为 15 - LOL(长度长度),其中 LOL 介于 2 和 4 之间(因为 SJCL 强制执行 <2^32 字节长度),并且是所需的字节数来描述消息的长度。这是 2 除非消息至少有 65536 字节长,在这种情况下它是 3,除非消息至少有 2^24 字节长,在这种情况下它是 4。请记住,如果您正在解密,则您传递的密文包含标签,但 LOL 必须根据不包含标签的消息长度计算。
通过这些更改,它应该可以工作:
#include <openssl/evp.h>
void handleErrors() {
abort();
}
int decryptccm(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad,
int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv,
unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
int ret;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
/* Initialise the decryption operation. */
if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_ccm(), NULL, NULL, NULL))
handleErrors();
int lol = 2;
if (ciphertext_len >= 1<<16) lol++;
if (ciphertext_len >= 1<<24) lol++;
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, 15-lol, NULL))
handleErrors();
/* Set expected tag value. */
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, 8, tag))
handleErrors();
/* Initialise key and IV */
if(1 != EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();
/* Provide the total ciphertext length
*/
if(1 != EVP_DecryptUpdate(ctx, NULL, &len, NULL, ciphertext_len))
handleErrors();
/* Provide any AAD data. This can be called zero or more times as
* required
*/
if(1 != EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len))
handleErrors();
/* Provide the message to be decrypted, and obtain the plaintext output.
* EVP_DecryptUpdate can be called multiple times if necessary
*/
ret = EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len);
plaintext_len = len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
if(ret > 0)
{
/* Success */
return plaintext_len;
}
else
{
/* Verify failed */
return -1;
}
}
int main(int argc, char **argv) {
// base64-decoded from your example
unsigned char iv[] = { 0x9F,0x62,0x54,0x4C,0x9D,0x3F,0xCA,0xB2,0xDD,0x08,0x33,0xDF,0x21,0xCA,0x80,0xCF };
unsigned char ct[] = { 0x14,0x2B,0x90,0x58,0x66,0x33,0xDE,0x89,0xC4,0xFE,0x54,0x6D,0xFF,0xBB,0xC2,0x97,0x90 };
unsigned char ky[] = { 0xD8,0xCC,0xAA,0x75 ,0x3E,0x29,0x83,0xF0 ,0x36,0x57,0xAB,0x3C ,0x8A,0x68,0xA8,0x5A ,0x9E,0x9F,0x1C,0xAC ,0x43,0xDA,0xB6,0x45 ,0x48,0x9C,0xDE,0x58 ,0x0A,0x9E,0xBD,0xAE };
const unsigned char *message = (const unsigned char *)"mymessage";
unsigned char plaintext[1000];
int ret = decryptccm(ct, 9, "", 0, &ct[9], ky, iv, plaintext);
plaintext[9] = 0;
printf("%d,%s\n",ret,plaintext);
return 0;
}
这个程序在我的机器上返回“9,mymessage”。