0. 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务 1. 使用OpenSSL的命令对你的8位学号(数字)进行加密解密,密钥的前8个字节为你的8位学号,提交过程截图(5')
2. 使用OpenSSL编程对对"你的8位学号(数字)"进行加密解密,提交代码和运行结果截图。(10’)
#include <openssl/evp.h>
#include <openssl/err.h>
#include <string.h>
void handleErrors(void) {
ERR_print_errors_fp(stderr);
abort();
}
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext) {
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
if(1 != EVP_EncryptInit_ex(ctx, EVP_sm4_cbc(), NULL, key, iv))
handleErrors();
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
unsigned char *iv, unsigned char *plaintext) {
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
if(1 != EVP_DecryptInit_ex(ctx, EVP_sm4_cbc(), NULL, key, iv))
handleErrors();
if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
handleErrors();
plaintext_len = len;
if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
plaintext_len += len;
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}
int main (void) {
unsigned char *key = (unsigned char *)"20211106";
unsigned char *iv = (unsigned char *)"0000000000000000";
unsigned char *plaintext = (unsigned char *)"20211106";
unsigned char ciphertext[128];
unsigned char decryptedtext[128];
int decryptedtext_len, ciphertext_len;
ciphertext_len = encrypt(plaintext, strlen ((char *)plaintext), key, iv, ciphertext);
decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv, decryptedtext);
decryptedtext[decryptedtext_len] = '\0';
printf("Ciphertext is:\n");
BIO_dump_fp (stdout, (const char *)ciphertext, ciphertext_len);
printf("Decrypted text is:\n");
printf("%s\n", decryptedtext);
return 0;
}
3. 使用龙脉智能钥匙完成 2的内容,并与OpenSSL的结果进行对比,提交代码和运行结果截图。((10’))
标签:ciphertext,plaintext,SM4,OpenSSL,len,unsigned,char,测试,EVP From: https://www.cnblogs.com/sjd-sr/p/18164957