- 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务
- 使用OpenSSL的命令对你的8位学号(数字)进行加密解密,密钥的前8个字节为你的8位学号,提交过程截图(5')
- 使用OpenSSL编程对对"你的8位学号(数字)"进行加密解密,提交代码和运行结果截图。(10’)
- 使用OpenSSL编程对内容为"所有同学的8位学号(数字)"的文件进行加密解密,密钥要包含你的8位学号,提交代码和运行结果截图。(选做(10’))
1. 使用OpenSSL的命令对你的8位学号(数字)进行加密解密
openssl enc -sm4-cbc -in 20201212.txt -out ciphertext.bin -K 2020121289abcdeffedcba9876543210 -iv 2020121289abcdeffedcba9876543210
![image](https://img2023.cnblogs.com/blog/2166406/202304/2166406-20230412100118494-1824775624.png)
2. 使用OpenSSL编程对"你的8位学号(数字)"进行加密解密
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/ec.h>
int main(int argc, char *argv[])
{
unsigned char sm4_en[512],sm4_de[512];
int sm4enStrLen,sm4deStrLen;
unsigned char source[7]={0x31,0x33,0x34,0x33,0x45,0x46,0x43};
unsigned char keyStr[16]={0x15,0x67,0x28,0xe1,0x5f,0x9a,0xfc,0x01,0xd4,0xb6,0x1b,0x4e,0x44,0x5d,0xbb,0x26};
sm4enStrLen=my_sm4encrpt(keyStr,source,7,sm4_en);
printf("sm4enStrLen:%d\n",sm4enStrLen);
for(int i=0;i<sm4enStrLen;++i)
{
printf("0x%x",sm4_en[i]);
}
printf("\n");
sm4deStrLen=dencryptStr(keyStr,sm4_en,sm4enStrLen,sm4_de);
printf("sm4deStrLen:%d\n",sm4deStrLen);
for(int i=0;i<7;++i)
{
printf("0x%x",sm4_de[i]);
}
printf("\n");
}
int my_sm4encrpt(unsigned char * keyStr,unsigned char * surbuf,int surlen,unsigned char * enbuf)
{
unsigned char *out_buf = enbuf;
int out_len;
int out_padding_len;
int i;
unsigned char *iv;
EVP_CIPHER_CTX *ctx;
ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit(ctx, EVP_sm4_ecb(), keyStr, iv);
if( 0 == surlen % 16 )
{
EVP_CIPHER_CTX_set_padding( ctx, 0 );
}
out_len = 0;
EVP_EncryptUpdate(ctx, out_buf, &out_len, surbuf, surlen);
out_padding_len = 0;
EVP_EncryptFinal(ctx, out_buf + out_len, &out_padding_len);
EVP_CIPHER_CTX_free(ctx);
return out_len + out_padding_len;
}
int dencryptStr(unsigned char * sm4PriKey, unsigned char *cEnStr, int cEnstrlen, unsigned char *deStr)
{
unsigned char *iv;
EVP_CIPHER_CTX *ctx;
int len;
int temlen;
int deStrLen;
if (!(ctx = EVP_CIPHER_CTX_new())) {
printf("EVP_CIPHER_CTX_new failed");
}
if (1 != EVP_DecryptInit(ctx, EVP_sm4_ecb(), sm4PriKey, iv)) {
printf("EVP_DecryptInit_ex failed");
}
if (1 != EVP_DecryptUpdate(ctx, deStr, &len, cEnStr, cEnstrlen)) {
printf("EVP_DecryptUpdate failed");
}
if( 0 == len % 16 )
{
EVP_CIPHER_CTX_set_padding( ctx, 0 );
len += 16;
}
if( !EVP_DecryptFinal( ctx, deStr + len, &temlen ) )
{
printf("EVP_DecryptFinal failed");
return EXIT_FAILURE;
}
deStrLen=len+temlen;
printf("解密数据:%d\n",deStrLen);
for (int i = 0;i < deStrLen;i++) {
printf("0x%02x ",*(deStr + i));
}
printf("\n");
EVP_CIPHER_CTX_free(ctx);
return deStrLen;
}
![image](https://img2023.cnblogs.com/blog/2166406/202304/2166406-20230412091120884-663643847.png)
3. 使用OpenSSL编程对内容为"所有同学的8位学号(数字)"的文件进行加密解密,密钥要包含你的8位学号
![image](https://img2023.cnblogs.com/blog/2166406/202304/2166406-20230412091727827-378178576.png)