1

我正在尝试在 Visual Studio 2015 中使用 lib-sodium 加密库。

以下是我的一段代码

unsigned char pk[crypto_box_PUBLICKEYBYTES];
unsigned char sk[crypto_box_SECRETKEYBYTES];

    crypto_box_keypair(pk, sk);
    cout << "\nPrivate Key: " << pk;
    cout << "\nSecret Key: " << sk;
    cout << "\n";

int m_len = 6, c_len = crypto_box_SEALBYTES + m_len;
unsigned char *m=NULL, *c=NULL;
m = (unsigned char *)sodium_malloc(m_len);
c = (unsigned char *)new unsigned char(c_len);
unsigned char *m2=NULL;
m2 = (unsigned char *) new unsigned char(m_len);

//Message to be encrpted
m[0] = 'M';
m[1] = 'C';
m[2] = '2';
m[3] = '2';
m[4] = '5';
m[5] = '\0';

cout << "\nMessage is: " << m;

if (crypto_box_seal(c, m, m_len, pk) != 0) {
    cout << "\nFail in cypto";
    return 1;
}

cout << "\nCrypted is: " << c;

if (crypto_box_seal_open(m2, c, c_len, pk, sk) != 0) {
    printf("crypto_box_seal_open() failure\n");
    return 1;
}
cout << "\nDecrypt is: " << m2;

问题如下:

  1. 每次运行代码时,我都会得到不同大小的公钥和私钥,但我使用的变量大小是恒定的。这怎么可能?

  2. 我正在尝试使用sodium_malloc函数为加密消息和解密消息分配内存。但它会违反访问错误的内存空间。这是一个问题,因为我正在用 C++ 编码还是有任何其他原因?

如果您需要有关此问题的任何其他信息,请告诉我。

4

0 回答 0