// rsa_encrypt_decrypt.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "crypt2.h"
#include "stdio.h"
#include "conio.h"
/*------------------------------------------------
Functionality Implemented:Encrypt and decrpt of RSA algorithm
--------------------------------------------------*/
int main(int argc, char* argv[])
{
	R_RSA_PUBLIC_KEY    RpubKey;
	R_RSA_PRIVATE_KEY   RpriKey;
	int nRet = 0;
	int i = 0,j=0;
	char bIn[128],bOut[128];
	unsigned int inLen =0,outLen=0;

	//generate RSA key pair
	printf("Generate a pair of RSA key...please wait......\n");
	nRet = R_GenerateRsaKeys(&RpubKey,&RpriKey);
	if(nRet != RE_SUCCESS)
		printf("error! return: 0x%04x",nRet);
	else
	{
		//print public key
		printf("RSA public key:\n");
		for(i = 0, j=0; i < sizeof(R_RSA_PUBLIC_KEY); i++,j++)
		{
			printf("%02x ", ((BYTE *)&RpubKey)[i]);
			if(j == 15)
			{
				printf("\n");
				j = -1;
			}
		}

		//print private key
		printf("\nRSA private key:\n");
		for(i = 0, j=0; i < sizeof(R_RSA_PRIVATE_KEY); i++,j++)
		{
			printf("%02x ", ((BYTE *)&RpriKey)[i]);
			if(j == 15)
			{
				printf("\n");
				j = -1;
			}
		}

	}

	printf("\n\nPlease input the length of plaintext:");
	scanf("%d",&inLen);
	printf("\nPlease input plaintext:");
	scanf("%s",bIn);

	//Encrypt
	//similar to the SES function _rsa_enc,the difference is that RSAPublicEncrypt 
	//function encrypts data with PKCS mode.
	nRet = RSAPublicEncrypt((unsigned char *)bOut,&outLen,(unsigned char *)bIn,inLen,&RpubKey);
	if(nRet != RE_SUCCESS)
		printf("\nerror! return: 0x%04x",nRet);
	else
	{
		printf("\nciphertext:\n");
		for(i = 0,j=0; i < outLen; i++,j++)
		{
			printf("%02x ", ((BYTE *)&bOut)[i]);
			if(j == 15)
			{
				printf("\n");
				j = -1;
			}
		}
		
		//Decrypt	
		printf("\nDecrypt ........\n");
		//Similar to the SES function _rsa_dec, the difference is RSAPrivateDecrypt
		//function decrypts data with PKCS mode.
		nRet = RSAPrivateDecrypt(
		(unsigned char *)bIn,
		&inLen,
		(unsigned char *)bOut,
		outLen,
		&RpriKey);
		if(nRet != RE_SUCCESS)
			printf("\nerror! return: 0x%04x",nRet);
		else
		{
			printf("\nplaintext:\n");
			for(i = 0,j=0; i < inLen; i++,j++)
			{
				printf("%02x ", ((BYTE *)&bIn)[i]);
				if(j == 15)
				{
					printf("\n");
					j = -1;
				}
			}
		}
	}
	getch();
	return 0;
}
