我正在嘗試使用 c 中的 openssl 庫添加兩個大數字,但我真的不知道如何使用它。
openssl 的檔案 - BN_add() 在這里https://www.openssl.org/docs/man3.0/man3/BN_add.html
//#include <openssl/bn.h>
//BN_add() adds a and b and places the result in r (r=a b).
//r may be the same BIGNUM as a or b.
int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
對我有什么a期望b?一個位元組陣列?一個字串?
任何在 openssl 中添加 bignumbers 并有一個簡單示例的人?
uj5u.com熱心網友回復:
要使用BN_add,您需要三個BIGNUM工件:您嘗試添加的兩個運算元和一個存盤結果的位置。運算元的來源可能會有所不同,這取決于源資料的性質和其中可能的轉換。應使用 獲取結果BN_new。
下面是一個使用兩個十進制數字字串的簡單示例:
#include <stdio.h>
#include <stdlib.h>
#include <openssl/bn.h>
#include <openssl/crypto.h>
int main()
{
const char n1[] = "12345678912345789123456789123456789";
const char n2[] = "12345678912345789123456789123456789";
BIGNUM *bn1 = NULL;
BN_dec2bn(&bn1, n1);
BIGNUM *bn2 = NULL;
BN_dec2bn(&bn2, n2);
BIGNUM *bn3 = BN_new();
BN_add(bn3, bn1, bn2);
char *n3 = BN_bn2dec(bn3);
printf("%s\n%s\n%s\n", n1, n2, n3);
OPENSSL_free(n3); // don't forget to free this.
BN_free(bn1);
BN_free(bn2);
BN_free(bn3);
return 0;
}
輸出
12345678912345789123456789123456789
12345678912345789123456789123456789
24691357824691578246913578246913578
請注意,我們確保釋放我們獲得的所有內容,其中包括將結果轉換為十進制字符字串,根據BN_bn2dec檔案,必須使用OPENSSL_free.
這不是唯一的方法,不同的方法高度依賴于源資料。例如,我們可以修改上面的程式,將兩個 256 位數字從 big-endian 位元組八位位元組轉換為BIGNUM. 為此,我們可以使用BN_bin2bn. 然而,其余代碼看起來相似(除了一些必須釋放的額外轉換緩沖區)。
#include <stdio.h>
#include <stdlib.h>
#include <openssl/bn.h>
#include <openssl/crypto.h>
#include <openssl/rand.h>
int main()
{
unsigned char n1[32];
unsigned char n2[32];
RAND_bytes(n1, sizeof n1);
RAND_bytes(n2, sizeof n2);
BIGNUM *bn1 = BN_bin2bn(n1, sizeof n1, NULL);
BIGNUM *bn2 = BN_bin2bn(n2, sizeof n2, NULL);
BIGNUM *bn3 = BN_new();
BN_add(bn3, bn1, bn2);
char *s1 = BN_bn2dec(bn1);
char *s2 = BN_bn2dec(bn2);
char *s3 = BN_bn2dec(bn3);
printf("%s\n%s\n%s\n", s1, s2, s3);
OPENSSL_free(s1);
OPENSSL_free(s2);
OPENSSL_free(s3);
BN_free(bn1);
BN_free(bn2);
BN_free(bn3);
return 0;
}
輸出(顯然不同)
12848991999079618356122471791635779303297173135339588614513279277444395635360
47516096440756489210553139954635811049213722081352926332729551875133172387567
60365088439836107566675611746271590352510895216692514947242831152577568022927
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/417141.html
標籤:
