📄 rsapki.c
字号:
/* * rsaPki.c * Release $Name: MATRIXSSL_1_7_3_OPEN $ * * RSA key and cert reading *//* * Copyright (c) PeerSec Networks, 2002-2005. All Rights Reserved. * The latest version of this code is available at http://www.matrixssl.org * * This software is open source; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This General Public License does NOT permit incorporating this software * into proprietary programs. If you are unable to comply with the GPL, a * commercial license for this software may be purchased from PeerSec Networks * at http://www.peersec.com * * This program is distributed in WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * http://www.gnu.org/copyleft/gpl.html */#ifdef VXWORKS#include <vxWorks.h>#endif /* VXWORKS */#ifndef WINCE #include <sys/stat.h> #include <signal.h>#endif /* WINCE */#include "pkiInternal.h"/* For our purposes USE_RSA is used to indicate RSA private key handling. USE_X509 indicates certificate handling and those blocks should be wrapped inside USE_RSA because that is the only key type currently supported*/#ifdef USE_RSA#define ATTRIB_COUNTRY_NAME 6#define ATTRIB_LOCALITY 7#define ATTRIB_ORGANIZATION 10#define ATTRIB_ORG_UNIT 11#define ATTRIB_DN_QUALIFIER 46#define ATTRIB_STATE_PROVINCE 8#define ATTRIB_COMMON_NAME 3#ifdef USE_3DESstatic const char encryptHeader[] = "DEK-Info: DES-EDE3-CBC,";static int32 hexToBinary(unsigned char *hex, unsigned char *bin, int32 binlen);#endifstatic int32 psAsnParsePrivateKey(psPool_t *pool, unsigned char **pp, int32 size, sslRsaKey_t *key);#endif /* USE_RSA *//******************************************************************************//* Open and close the PKI module. These routines are called once in the lifetime of the application and initialize and clean up the library respectively.*/int32 matrixPkiOpen(){ if (sslOpenOsdep() < 0) { matrixStrDebugMsg("Osdep open failure\n", NULL); return -1; } return 0;}void matrixPkiClose(){ sslCloseOsdep();}#ifdef USE_FILE_SYSTEM/******************************************************************************//* Return the file contents given a file name in a single allocated buffer. Not a good routine to use generally with the fixed mem stuff. Not actually doing a 'binary' file read. Only using the 'r' attribute since all the cert and key files are text.*/int32 psGetFileBin(psPool_t *pool, char *fileName, unsigned char **bin, int32 *binLen){ FILE *fp; struct stat fstat; size_t tmp = 0; *binLen = 0; *bin = NULL; if (fileName == NULL) { return -1; } if ((stat(fileName, &fstat) != 0) || (fp = fopen(fileName, "r")) == NULL) { return -7; /* FILE_NOT_FOUND */ } *bin = psMalloc(pool, fstat.st_size); if (*bin == NULL) { return -8; /* SSL_MEM_ERROR */ } while (((tmp = fread(*bin + *binLen, sizeof(char), 512, fp)) > 0) && (*binLen < fstat.st_size)) { *binLen += (int32)tmp; } fclose(fp); return 0;}/******************************************************************************//* * Public API to return an ASN.1 encoded key stream from a PEM private * key file * * If password is provided, we only deal with 3des cbc encryption * Function allocates key on success. User must free. */int32 matrixRsaReadPrivKey(psPool_t *pool, char *fileName, char *password, char **keyMem, int32 *keyMemLen){ char *start, *end; unsigned char *keyBuf, *DERout; int32 keyBufLen, rc, DERlen, PEMlen = 0;#ifdef USE_3DES sslCipherContext_t ctx; unsigned char passKey[SSL_DES3_KEY_LEN]; unsigned char cipherIV[SSL_DES3_IV_LEN]; int32 tmp, encrypted = 0;#endif /* USE_3DES */ if (fileName == NULL) { return 0; } *keyMem = NULL; if ((rc = psGetFileBin(pool, fileName, &keyBuf, &keyBufLen)) < 0) { return rc; } start = end = NULL;/* * Check header and encryption parameters. */ if ((start = strstr(keyBuf, "-----BEGIN RSA PRIVATE KEY-----")) == NULL) { matrixStrDebugMsg("Error parsing private key buffer\n", NULL); psFree(keyBuf); return -1; } start += strlen("-----BEGIN RSA PRIVATE KEY-----"); while (*start == '\r' || *start == '\n') { start++; } if (strstr(keyBuf, "Proc-Type:") && strstr(keyBuf, "4,ENCRYPTED")) {#ifdef USE_3DES encrypted++; if (password == NULL) { matrixStrDebugMsg("No password given for encrypted private key\n", NULL); psFree(keyBuf); return -1; } if ((start = strstr(keyBuf, encryptHeader)) == NULL) { matrixStrDebugMsg("Unrecognized private key file encoding\n", NULL); psFree(keyBuf); return -1; } start += strlen(encryptHeader); /* SECURITY - we assume here that header points to at least 16 bytes of data */ tmp = hexToBinary((unsigned char*)start, cipherIV, SSL_DES3_IV_LEN); if (tmp < 0) { matrixStrDebugMsg("Invalid private key file salt\n", NULL); psFree(keyBuf); return -1; } start += tmp; generate3DESKey((unsigned char*)password, (int32)strlen(password), cipherIV, (unsigned char*)passKey);#else /* !USE_3DES *//* * The private key is encrypted, but 3DES support has been turned off */ matrixStrDebugMsg("3DES has been disabled for private key decrypt\n", NULL); psFree(keyBuf); return -1; #endif /* USE_3DES */ } if ((end = strstr(keyBuf, "-----END RSA PRIVATE KEY-----")) == NULL) { matrixStrDebugMsg("Error parsing private key buffer\n", NULL); psFree(keyBuf); return -1; } PEMlen = (int32)(end - start);/* Take the raw input and do a base64 decode */ DERout = psMalloc(pool, PEMlen); if (DERout == NULL) { return -8; /* SSL_MEM_ERROR */ } DERlen = PEMlen; if (ps_base64_decode((unsigned char*)start, PEMlen, DERout, &DERlen) != 0) { psFree(DERout); psFree(keyBuf); matrixStrDebugMsg("Unable to base64 decode private key\n", NULL); return -1; } psFree(keyBuf);#ifdef USE_3DES/* * Decode */ if (encrypted == 1 && password) { matrix3desInit(&ctx, cipherIV, passKey, SSL_DES3_KEY_LEN); matrix3desDecrypt(&ctx, DERout, DERout, DERlen); }#endif /* USE_3DES *//* Don't parse this here. Return the ASN.1 encoded buf to be consistent with the other mem APIs. Use the ParsePrivKey function if you want the structure format*/ *keyMem = DERout; *keyMemLen = DERlen; return rc;}#ifdef USE_3DES/******************************************************************************//* Convert an ASCII hex representation to a binary buffer. Decode enough data out of 'hex' buffer to produce 'binlen' bytes in 'bin' Two digits of ASCII hex map to the high and low nybbles (in that order), so this function assumes that 'hex' points to 2x 'binlen' bytes of data. Return the number of bytes processed from hex (2x binlen) or < 0 on error.*/static int32 hexToBinary(unsigned char *hex, unsigned char *bin, int32 binlen){ unsigned char *end, c, highOrder; highOrder = 1; for (end = hex + binlen * 2; hex < end; hex++) { c = *hex; if ('0' <= c && c <='9') { c -= '0'; } else if ('a' <= c && c <='f') { c -= ('a' - 10); } else if ('A' <= c && c <='F') { c -= ('A' - 10); } else { return -1; } if (highOrder++ & 0x1) { *bin = c << 4; } else { *bin |= c; bin++; } } return binlen * 2;}#endif /* USE_3DES */#endif /* USE_FILE_SYSTEM *//******************************************************************************//* * In memory version of matrixRsaReadPrivKey. The keyBuf is the raw * ASN.1 encoded buffer. */int32 matrixRsaParsePrivKey(psPool_t *pool, unsigned char *keyBuf, int32 keyBufLen, sslRsaKey_t **key){ unsigned char *asnp;/* Now have the DER stream to extract from in asnp */ *key = psMalloc(pool, sizeof(sslRsaKey_t)); if (*key == NULL) { return -8; /* SSL_MEM_ERROR */ } memset(*key, 0x0, sizeof(sslRsaKey_t)); asnp = keyBuf; if (psAsnParsePrivateKey(pool, &asnp, keyBufLen, *key) < 0) { matrixRsaFreeKey(*key); *key = NULL; matrixStrDebugMsg("Unable to ASN parse private key.\n", NULL); return -1; } return 0;}/******************************************************************************//* * Free an RSA key. mp_clear will zero the memory of each element and free it. */void matrixRsaFreeKey(sslRsaKey_t *key){
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -