Exemple #1
0
int main(int argc,char *argv[])
{
    if(argc < 2)
    {
        printf("usage:\n");
        printf("%s string.\n",argv[0]);
        return 0;
    }
    char *encdata = NULL;
    int encLen = (strlen(argv[1])/16+1)*16;
    encdata = malloc(encLen);

	sm4_context ctx;
	sm4_setkey_enc(&ctx,key);
    sm4_crypt_ecb(&ctx,1,strlen((const char *)argv[1]),argv[1],encdata);
    printf("Enc Data[%d] :",encLen);
    printHex(encdata,encLen);

    char *decdata = malloc(encLen);
   sm4_setkey_dec(&ctx,key);
   sm4_crypt_ecb(&ctx,0,encLen,encdata,decdata);

   printf("Dec Data:%s\n",decdata);


   free(encdata);
   free(decdata);
}
Exemple #2
0
int crypt_dec_block(cipher_context *cctx, uint8 *in, uint8 *out, int len)
{
	if(len%cctx->block_size)
		return 0;
		
	switch(cctx->alg){
	case ALG_AES_ECB:
	case ALG_AES_CTR:
	{
		int j;

		for(j=0; j<len; j+=cctx->block_size){
			AES_decrypt(in+j, out+j, cctx->enc_ctx);
		}
		return 1;
	}
	case ALG_AES_CBC:
	{
		int i, j;
		uint8 temp[MAX_CIPHER_BLOCK_SIZE];

		for(j=0; j<len; j+=cctx->block_size){
			memcpy(temp, in+j, cctx->block_size);
			AES_decrypt(temp, out+j, cctx->enc_ctx);
			for(i=0; i<cctx->block_size; i++){
				out[j+i]^=cctx->iv[i];
			}
			
			memcpy(cctx->iv, temp, cctx->block_size);
		}
		return 1;
	}
	case ALG_SM4_ECB:
	case ALG_SM4_CTR:
		sm4_crypt_ecb(cctx->enc_ctx, SM4_DECRYPT, len, in, out);
		return 1;
		break;
	case ALG_SM4_CBC:
		sm4_crypt_cbc(cctx->enc_ctx, SM4_DECRYPT, len, cctx->iv, in, out);
		return 1;
		break;
	}
	
	return 0;
}
Exemple #3
0
int crypt_enc_block(cipher_context *cctx, uint8 *in, uint8 *out, int len)
{
	if(len%cctx->block_size)
		return 0;
		
	switch(cctx->alg){
	case ALG_AES_ECB:
	case ALG_AES_CTR:
	{
		int j;

		for(j=0; j<len; j+=cctx->block_size){
			AES_encrypt(in+j, out+j, cctx->enc_ctx);
		}
		return 1;
	}
	case ALG_AES_CBC:
	{
		int i, j;
		uint8* piv;
		uint8 temp[MAX_CIPHER_BLOCK_SIZE];

		piv=cctx->iv;
		for(j=0; j<len; j+=cctx->block_size){
			for(i=0; i<cctx->block_size; i++)
				temp[i]=in[j+i]^piv[i];
			AES_encrypt(temp, out+j, cctx->enc_ctx);
			piv=out+j;
		}

		memcpy(cctx->iv, out+j-cctx->block_size, cctx->block_size);
		return 1;
	}
	case ALG_SM4_ECB:
	case ALG_SM4_CTR:
		sm4_crypt_ecb(cctx->enc_ctx, SM4_ENCRYPT, len, in, out);
		return 1;
	case ALG_SM4_CBC:
		sm4_crypt_cbc(cctx->enc_ctx, SM4_ENCRYPT, len, cctx->iv, in, out);
		return 1;
	}
	
	return 0;
}