openssl C++ ecdsa 签名和验签
时间: 2023-11-12 08:07:15 浏览: 240
基于OpenSSL库的ECDSA签名与验证1
ECDSA(Elliptic Curve Digital Signature Algorithm)是一种基于椭圆曲线密码学的数字签名算法。OpenSSL库提供了ECDSA签名和验签的函数。
ECDSA签名:
1. 生成ECDSA密钥对:
```
EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
EC_KEY_generate_key(key);
```
2. 计算消息的哈希值:
```
unsigned char *msg = "Hello World";
unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256(msg, strlen(msg), digest);
```
3. 对消息哈希值进行签名:
```
unsigned char *signature;
unsigned int signature_len;
signature = (unsigned char *)malloc(ECDSA_size(key));
ECDSA_sign(0, digest, SHA256_DIGEST_LENGTH, signature, &signature_len, key);
```
4. 将签名结果进行编码:
```
unsigned char *encoded_signature;
unsigned int encoded_signature_len;
encoded_signature = (unsigned char *)malloc(signature_len * 2 + 1);
ECDSA_signature_encode(ECDSA_SIG_new(), signature, signature_len, encoded_signature, &encoded_signature_len);
```
ECDSA验签:
1. 解码签名结果:
```
ECDSA_SIG *ecdsa_sig = ECDSA_SIG_new();
unsigned char *encoded_signature = "304402202a24c7d48f6a..."; // 签名结果
unsigned int encoded_signature_len = strlen(encoded_signature);
ECDSA_signature_decode(ecdsa_sig, encoded_signature, encoded_signature_len);
```
2. 计算消息的哈希值:
```
unsigned char *msg = "Hello World";
unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256(msg, strlen(msg), digest);
```
3. 进行验签:
```
int result = ECDSA_do_verify(digest, SHA256_DIGEST_LENGTH, ecdsa_sig, key);
if (result == 1) {
printf("Signature verified successfully.\n");
} else if (result == 0) {
printf("Signature verification failed.\n");
} else {
printf("Error occurred during signature verification.\n");
}
```
完整的示例代码:
```
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
#include <openssl/sha.h>
int main() {
EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); // 选择椭圆曲线
EC_KEY_generate_key(key); // 生成密钥对
// 签名
unsigned char *msg = "Hello World";
unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256(msg, strlen(msg), digest); // 计算哈希值
unsigned char *signature;
unsigned int signature_len;
signature = (unsigned char *)malloc(ECDSA_size(key));
ECDSA_sign(0, digest, SHA256_DIGEST_LENGTH, signature, &signature_len, key); // 进行签名
unsigned char *encoded_signature;
unsigned int encoded_signature_len;
encoded_signature = (unsigned char *)malloc(signature_len * 2 + 1);
ECDSA_signature_encode(ECDSA_SIG_new(), signature, signature_len, encoded_signature, &encoded_signature_len); // 编码签名结果
// 验签
ECDSA_SIG *ecdsa_sig = ECDSA_SIG_new();
ECDSA_signature_decode(ecdsa_sig, encoded_signature, encoded_signature_len); // 解码签名结果
int result = ECDSA_do_verify(digest, SHA256_DIGEST_LENGTH, ecdsa_sig, key); // 进行验签
if (result == 1) {
printf("Signature verified successfully.\n");
} else if (result == 0) {
printf("Signature verification failed.\n");
} else {
printf("Error occurred during signature verification.\n");
}
ECDSA_SIG_free(ecdsa_sig);
EC_KEY_free(key);
free(signature);
free(encoded_signature);
return 0;
}
```
阅读全文