How to do RSA encryption?

  • Author
    Posts
  • #4124
    Chris Torr
    Keymaster
    August 7, 2020

    Here is an example of generating an RSA key and performing encryption with it.

    
    #include <multos.h>
    
    #define MODULUS_LENGTH ((WORD)256)
    #define EXPONENT_LENGTH 1
    #define KEYGEN_METHOD_DEFAULT 0
    #define KEYGEN_MODE_BALANCED 1
    
    typedef struct
    {
    	BYTE privateKey[(MODULUS_LENGTH)/2 * 5];// Formatted as dp|dq|p|q|u
    	BYTE publicKey[MODULUS_LENGTH];
    	BYTE exponent[1];
    } rsa_t;
    
    #pragma melstatic
    rsa_t keyPair;
    
    #pragma melsession
    BYTE ciphertext[MODULUS_LENGTH];
    BYTE deciphered[MODULUS_LENGTH];
    
    	// ... in the code ...
    	// Generate a key pair
    	keyPair.exponent[0] = 3;	
    	genOK = multosGenerateRsaKeyPair(KEYGEN_METHOD_DEFAULT,
    					KEYGEN_MODE_BALANCED,
    					MODULUS_LENGTH,
    					keyPair.publicKey,
    					keyPair.privateKey,
    					keyPair.exponent,
    					EXPONENT_LENGTH,
    					MODULUS_LENGTH);
    									
    	if(!genOK)	// a BOOL
    		multosExitSW(0x90FD);
    
    	// Encrypt
    	multosRsaVerify(ciphertext,
    			cleartext,		// A BYTE array of size MODULUS_LENGTH containing the data to encipher
    			keyPair.publicKey,
    			keyPair.exponent,
    			MODULUS_LENGTH,
    			EXPONENT_LENGTH);
    
    	// Decrypt
    	multosModularExponentiationCRT(deciphered,
    					ciphertext,
    					keyPair.privateKey+MODULUS_LENGTH,	//pquAddr
    					keyPair.privateKey,			//dpdqAddr
    					MODULUS_LENGTH);
    
    	// Compare deciphered with original cleartext - should be the same
    	if(multosCompare(deciphered,cleartext,MODULUS_LENGTH) != MULTOS_BLOCK1_EQ_BLOCK2)
    		multosExitSW(0x90FF);
    }
    
  • You must be logged in to reply to this topic.