Path: blob/master/libs/tomcrypt/src/pk/rsa/rsa_export.c
4396 views
/* LibTomCrypt, modular cryptographic library -- Tom St Denis1*2* LibTomCrypt is a library that provides various cryptographic3* algorithms in a highly modular and flexible manner.4*5* The library is free for all purposes without any express6* guarantee it works.7*/8#include "tomcrypt.h"910/**11@file rsa_export.c12Export RSA PKCS keys, Tom St Denis13*/1415#ifdef LTC_MRSA1617/**18This will export either an RSAPublicKey or RSAPrivateKey [defined in PKCS #1 v2.1]19@param out [out] Destination of the packet20@param outlen [in/out] The max size and resulting size of the packet21@param type The type of exported key (PK_PRIVATE or PK_PUBLIC)22@param key The RSA key to export23@return CRYPT_OK if successful24*/25int rsa_export(unsigned char *out, unsigned long *outlen, int type, rsa_key *key)26{27unsigned long zero=0;28int err;29LTC_ARGCHK(out != NULL);30LTC_ARGCHK(outlen != NULL);31LTC_ARGCHK(key != NULL);3233/* type valid? */34if (!(key->type == PK_PRIVATE) && (type == PK_PRIVATE)) {35return CRYPT_PK_INVALID_TYPE;36}3738if (type == PK_PRIVATE) {39/* private key */40/* output is41Version, n, e, d, p, q, d mod (p-1), d mod (q - 1), 1/q mod p42*/43return der_encode_sequence_multi(out, outlen,44LTC_ASN1_SHORT_INTEGER, 1UL, &zero,45LTC_ASN1_INTEGER, 1UL, key->N,46LTC_ASN1_INTEGER, 1UL, key->e,47LTC_ASN1_INTEGER, 1UL, key->d,48LTC_ASN1_INTEGER, 1UL, key->p,49LTC_ASN1_INTEGER, 1UL, key->q,50LTC_ASN1_INTEGER, 1UL, key->dP,51LTC_ASN1_INTEGER, 1UL, key->dQ,52LTC_ASN1_INTEGER, 1UL, key->qP,53LTC_ASN1_EOL, 0UL, NULL);54} else {55/* public key */56unsigned long tmplen, *ptmplen;57unsigned char* tmp = NULL;5859if (type & PK_STD) {60tmplen = (unsigned long)(mp_count_bits(key->N) / 8) * 2 + 8;61tmp = XMALLOC(tmplen);62ptmplen = &tmplen;63if (tmp == NULL) {64return CRYPT_MEM;65}66}67else {68tmp = out;69ptmplen = outlen;70}7172err = der_encode_sequence_multi(tmp, ptmplen,73LTC_ASN1_INTEGER, 1UL, key->N,74LTC_ASN1_INTEGER, 1UL, key->e,75LTC_ASN1_EOL, 0UL, NULL);7677if ((err != CRYPT_OK) || !(type & PK_STD)) {78goto finish;79}8081err = der_encode_subject_public_key_info(out, outlen,82PKA_RSA, tmp, tmplen, LTC_ASN1_NULL, NULL, 0);8384finish:85if (tmp != out)86XFREE(tmp);87return err;8889}90}9192#endif /* LTC_MRSA */939495