1/* 2 * encrypt/decrypt using CSP implementation of AES. 3 */ 4#include "enDecrypt.h" 5#include <Security/cssm.h> 6#include "cspwrap.h" 7#include "common.h" 8#include <strings.h> 9 10static CSSM_CSP_HANDLE cspHand = 0; 11 12CSSM_RETURN encryptDecryptCsp( 13 CSSM_BOOL forEncrypt, 14 uint32 keySizeInBits, 15 uint32 blockSizeInBits, 16 const uint8 *key, // raw key bytes 17 const uint8 *inText, 18 uint32 inTextLen, 19 uint8 *outText) 20{ 21 CSSM_KEY_PTR symKey; // mallocd by cspGenSymKey or a ptr 22 // to refKey 23 CSSM_RETURN crtn; 24 CSSM_DATA inData; 25 CSSM_DATA outData; 26 27 if(cspHand == 0) { 28 /* attach first time thru */ 29 cspHand = cspDlDbStartup(CSSM_TRUE, NULL); 30 if(cspHand == 0) { 31 return CSSMERR_CSSM_MODULE_NOT_LOADED; 32 } 33 } 34 35 /* cook up a raw symmetric key */ 36 symKey = cspGenSymKey(cspHand, 37 CSSM_ALGID_AES, 38 "noLabel", 39 8, 40 CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_DECRYPT, 41 keySizeInBits, 42 CSSM_FALSE); // ref key 43 if(symKey == NULL) { 44 return CSSM_ERRCODE_INTERNAL_ERROR; 45 } 46 memmove(symKey->KeyData.Data, key, keySizeInBits / 8); 47 48 inData.Data = (uint8 *)inText; 49 inData.Length = inTextLen; 50 outData.Data = outText; 51 outData.Length = inTextLen; 52 53 if(forEncrypt) { 54 crtn = cspEncrypt(cspHand, 55 CSSM_ALGID_AES, 56 CSSM_ALGMODE_ECB, 57 CSSM_PADDING_NONE, 58 symKey, 59 NULL, // no second key 60 0, // effectiveKeyBits 61 0, // rounds 62 NULL, // iv 63 &inData, 64 &outData, 65 CSSM_FALSE); // mallocCtext 66 } 67 else { 68 crtn = cspDecrypt(cspHand, 69 CSSM_ALGID_AES, 70 CSSM_ALGMODE_ECB, 71 CSSM_PADDING_NONE, 72 symKey, 73 NULL, // no second key 74 0, // effectiveKeyBits 75 0, // rounds 76 NULL, // iv 77 &inData, 78 &outData, 79 CSSM_FALSE); // mallocPtext 80 } 81 cspFreeKey(cspHand, symKey); 82 return crtn; 83 84} 85