GmSSL3.1中未提供SM4 ofb模式加解密示例程序(GmSSL1.0库中有实现),给出如下示例供参考。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gmssl/sm4.h>
typedef void (*block128_f) (const void *key,const unsigned char in[16],
unsigned char out[16]);
void CRYPTO_ofb128_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16], int *num, block128_f block) {
unsigned int n;
size_t l = 0;
n = *num;
while (l < len) {
if (n == 0) {
(*block)(key, ivec, ivec);
}
out[l] = in[l] ^ ivec[n];
// printf("in[%d]=%02X,ivec[%d}=%02X --> out[%d]=%02X\n", l, in[l], n, ivec[n], l, out[l]);
++l;
n = (n + 1) % 16;
}
*num = n;
}
int main(void)
{
SM4_KEY sm4_key;
unsigned char iv[16]={0x91 ,0xba ,0x69 ,0x2f ,0x63 ,0x01 ,0xdf ,0x3a ,0x3e ,0x14 ,0xd4 ,0x9a ,0x63 ,0xca ,0x94 ,0xe7};
unsigned char key[16]={0x35 ,0x01 ,0xb1 ,0x98 ,0x11 ,0x99 ,0x7b ,0xe1 ,0xf1 ,0x1f ,0x23 ,0x76 ,0x45 ,0x8c ,0xba ,0x41};
unsigned char mbuf[32] = {0x35 ,0x01 ,0xb1 ,0x98 ,0x11 ,0x99 ,0x7b ,0xe1 ,0xf1 ,0x1f ,0x23 ,0x76 ,0x45 ,0x8c ,0xba ,0x41 ,
0x91 ,0xba ,0x69 ,0x2f ,0x63 ,0x01 ,0xdf ,0x3a ,0x3e ,0x14 ,0xd4 ,0x9a ,0x63 ,0xca ,0x94 ,0xe7};
unsigned char cbuf[32] = {0};
unsigned char pbuf[32] = {0};
int i;
printf("key: ");
for (i = 0; i < sizeof(key); i++) {
printf("%02X", key[i]);
}
printf("\n");
printf("iv: ");
for (i = 0; i < sizeof(iv); i++) {
printf("%02X", iv[i]);
}
printf("\n");
printf("plaintext: ");
for (i = 0; i < sizeof(mbuf); i++) {
printf("%02X", mbuf[i]);
}
printf("\n");
int num = 0;
sm4_set_encrypt_key(&sm4_key, key);
CRYPTO_ofb128_encrypt( mbuf, cbuf, 32, &sm4_key, iv, &num, &sm4_encrypt);
printf("ciphertext: ");
for (i = 0; i < sizeof(cbuf); i++) {
printf("0x%02X,", cbuf[i]);
}
printf("\n");
unsigned char iv1[16]={0x91 ,0xba ,0x69 ,0x2f ,0x63 ,0x01 ,0xdf ,0x3a ,0x3e ,0x14 ,0xd4 ,0x9a ,0x63 ,0xca ,0x94 ,0xe7};
CRYPTO_ofb128_encrypt( cbuf, pbuf, 32, &sm4_key, iv1, &num, &sm4_encrypt);
printf("decrypted: ");
for (i = 0; i < sizeof(pbuf); i++) {
printf("%02X", pbuf[i]);
}
printf("\n");
return 0;
}