PageRenderTime 101ms CodeModel.GetById 22ms app.highlight 70ms RepoModel.GetById 1ms app.codeStats 0ms

/security/nss/lib/softoken/lowpbe.c

http://github.com/zpao/v8monkey
C | 1410 lines | 1073 code | 176 blank | 161 comment | 330 complexity | 082196e4487d2e02e6204c551ced476f MD5 | raw file
   1/* ***** BEGIN LICENSE BLOCK *****
   2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
   3 *
   4 * The contents of this file are subject to the Mozilla Public License Version
   5 * 1.1 (the "License"); you may not use this file except in compliance with
   6 * the License. You may obtain a copy of the License at
   7 * http://www.mozilla.org/MPL/
   8 *
   9 * Software distributed under the License is distributed on an "AS IS" basis,
  10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11 * for the specific language governing rights and limitations under the
  12 * License.
  13 *
  14 * The Original Code is the Netscape security libraries.
  15 *
  16 * The Initial Developer of the Original Code is
  17 * Netscape Communications Corporation.
  18 * Portions created by the Initial Developer are Copyright (C) 1994-2000
  19 * the Initial Developer. All Rights Reserved.
  20 *
  21 * Contributor(s):
  22 *
  23 * Alternatively, the contents of this file may be used under the terms of
  24 * either the GNU General Public License Version 2 or later (the "GPL"), or
  25 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  26 * in which case the provisions of the GPL or the LGPL are applicable instead
  27 * of those above. If you wish to allow use of your version of this file only
  28 * under the terms of either the GPL or the LGPL, and not to allow others to
  29 * use your version of this file under the terms of the MPL, indicate your
  30 * decision by deleting the provisions above and replace them with the notice
  31 * and other provisions required by the GPL or the LGPL. If you do not delete
  32 * the provisions above, a recipient may use your version of this file under
  33 * the terms of any one of the MPL, the GPL or the LGPL.
  34 *
  35 * ***** END LICENSE BLOCK ***** */
  36
  37#include "plarena.h"
  38
  39#include "seccomon.h"
  40#include "secitem.h"
  41#include "secport.h"
  42#include "hasht.h"
  43#include "pkcs11t.h"
  44#include "blapi.h"
  45#include "hasht.h"
  46#include "secasn1.h"
  47#include "secder.h"
  48#include "lowpbe.h"
  49#include "secoid.h"
  50#include "alghmac.h"
  51#include "softoken.h"
  52#include "secerr.h"
  53
  54SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate)
  55
  56/* template for PKCS 5 PBE Parameter.  This template has been expanded
  57 * based upon the additions in PKCS 12.  This should eventually be moved
  58 * if RSA updates PKCS 5.
  59 */
  60static const SEC_ASN1Template NSSPKCS5PBEParameterTemplate[] =
  61{
  62    { SEC_ASN1_SEQUENCE, 
  63	0, NULL, sizeof(NSSPKCS5PBEParameter) },
  64    { SEC_ASN1_OCTET_STRING, 
  65	offsetof(NSSPKCS5PBEParameter, salt) },
  66    { SEC_ASN1_INTEGER,
  67	offsetof(NSSPKCS5PBEParameter, iteration) },
  68    { 0 }
  69};
  70
  71static const SEC_ASN1Template NSSPKCS5PKCS12V2PBEParameterTemplate[] =
  72{   
  73    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSPKCS5PBEParameter) },
  74    { SEC_ASN1_OCTET_STRING, offsetof(NSSPKCS5PBEParameter, salt) },
  75    { SEC_ASN1_INTEGER, offsetof(NSSPKCS5PBEParameter, iteration) },
  76    { 0 }
  77};
  78
  79
  80/* PKCS5 v2 */
  81
  82struct nsspkcs5V2PBEParameterStr {
  83    SECAlgorithmID keyParams;  /* parameters of the key generation */
  84    SECAlgorithmID algParams;  /* parameters for the encryption or mac op */
  85};
  86
  87typedef struct nsspkcs5V2PBEParameterStr nsspkcs5V2PBEParameter;
  88#define PBKDF2
  89
  90#ifdef PBKDF2
  91static const SEC_ASN1Template NSSPKCS5V2PBES2ParameterTemplate[] =
  92{   
  93    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(nsspkcs5V2PBEParameter) },
  94    { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
  95        offsetof(nsspkcs5V2PBEParameter, keyParams), 
  96        SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
  97    { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
  98        offsetof(nsspkcs5V2PBEParameter, algParams),
  99        SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
 100    { 0 }
 101};
 102
 103static const SEC_ASN1Template NSSPKCS5V2PBEParameterTemplate[] =
 104{   
 105    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSPKCS5PBEParameter) },
 106    /* this is really a choice, but since we don't understand any other
 107     *choice, just inline it. */
 108    { SEC_ASN1_OCTET_STRING, offsetof(NSSPKCS5PBEParameter, salt) },
 109    { SEC_ASN1_INTEGER, offsetof(NSSPKCS5PBEParameter, iteration) },
 110    { SEC_ASN1_INTEGER, offsetof(NSSPKCS5PBEParameter, keyLength) },
 111    { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
 112        offsetof(NSSPKCS5PBEParameter, prfAlg),
 113        SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
 114    { 0 }
 115};
 116#endif
 117
 118SECStatus
 119nsspkcs5_HashBuf(const SECHashObject *hashObj, unsigned char *dest,
 120					 unsigned char *src, int len)
 121{
 122    void *ctx;
 123    unsigned int retLen;
 124
 125    ctx = hashObj->create();
 126    if(ctx == NULL) {
 127	return SECFailure;
 128    }
 129    hashObj->begin(ctx);
 130    hashObj->update(ctx, src, len);
 131    hashObj->end(ctx, dest, &retLen, hashObj->length);
 132    hashObj->destroy(ctx, PR_TRUE);
 133    return SECSuccess;
 134}
 135
 136/* generate bits using any hash
 137 */
 138static SECItem *
 139nsspkcs5_PBKDF1(const SECHashObject *hashObj, SECItem *salt, SECItem *pwd, 
 140						int iter, PRBool faulty3DES) 
 141{
 142    SECItem *hash = NULL, *pre_hash = NULL;
 143    SECStatus rv = SECFailure;
 144
 145    if((salt == NULL) || (pwd == NULL) || (iter < 0)) {
 146	return NULL;
 147    }
 148	
 149    hash = (SECItem *)PORT_ZAlloc(sizeof(SECItem));
 150    pre_hash = (SECItem *)PORT_ZAlloc(sizeof(SECItem));
 151
 152    if((hash != NULL) && (pre_hash != NULL)) {
 153	int i, ph_len;
 154
 155	ph_len = hashObj->length;
 156	if((salt->len + pwd->len) > hashObj->length) {
 157	    ph_len = salt->len + pwd->len;
 158	}
 159
 160	rv = SECFailure;
 161
 162	/* allocate buffers */
 163	hash->len = hashObj->length;
 164	hash->data = (unsigned char *)PORT_ZAlloc(hash->len);
 165	pre_hash->data = (unsigned char *)PORT_ZAlloc(ph_len);
 166
 167	/* in pbeSHA1TripleDESCBC there was an allocation error that made
 168	 * it into the caller.  We do not want to propagate those errors
 169	 * further, so we are doing it correctly, but reading the old method.
 170	 */
 171	if (faulty3DES) {
 172	    pre_hash->len = ph_len;
 173	} else {
 174	    pre_hash->len = salt->len + pwd->len;
 175	}
 176
 177	/* preform hash */
 178	if ((hash->data != NULL) && (pre_hash->data != NULL)) {
 179	    rv = SECSuccess;
 180	    /* check for 0 length password */
 181	    if(pwd->len > 0) {
 182		PORT_Memcpy(pre_hash->data, pwd->data, pwd->len);
 183	    }
 184	    if(salt->len > 0) {
 185		PORT_Memcpy((pre_hash->data+pwd->len), salt->data, salt->len);
 186	    }
 187	    for(i = 0; ((i < iter) && (rv == SECSuccess)); i++) {
 188		rv = nsspkcs5_HashBuf(hashObj, hash->data, 
 189					pre_hash->data, pre_hash->len);
 190		if(rv != SECFailure) {
 191		    pre_hash->len = hashObj->length;
 192		    PORT_Memcpy(pre_hash->data, hash->data, hashObj->length);
 193		}
 194	    }
 195	}
 196    }
 197
 198    if(pre_hash != NULL) {
 199	SECITEM_FreeItem(pre_hash, PR_TRUE);
 200    }
 201
 202    if((rv != SECSuccess) && (hash != NULL)) {
 203	SECITEM_FreeItem(hash, PR_TRUE);
 204	hash = NULL;
 205    }
 206
 207    return hash;
 208}
 209
 210/* this bit generation routine is described in PKCS 12 and the proposed
 211 * extensions to PKCS 5.  an initial hash is generated following the
 212 * instructions laid out in PKCS 5.  If the number of bits generated is
 213 * insufficient, then the method discussed in the proposed extensions to
 214 * PKCS 5 in PKCS 12 are used.  This extension makes use of the HMAC
 215 * function.  And the P_Hash function from the TLS standard.
 216 */
 217static SECItem *
 218nsspkcs5_PFXPBE(const SECHashObject *hashObj, NSSPKCS5PBEParameter *pbe_param,
 219				SECItem *init_hash, unsigned int bytes_needed)
 220{
 221    SECItem *ret_bits = NULL;
 222    int hash_size = 0;
 223    unsigned int i;
 224    unsigned int hash_iter;
 225    unsigned int dig_len;
 226    SECStatus rv = SECFailure;
 227    unsigned char *state = NULL;
 228    unsigned int state_len;
 229    HMACContext *cx = NULL;
 230
 231    hash_size = hashObj->length;
 232    hash_iter = (bytes_needed + (unsigned int)hash_size - 1) / hash_size;
 233
 234    /* allocate return buffer */
 235    ret_bits = (SECItem  *)PORT_ZAlloc(sizeof(SECItem));
 236    if(ret_bits == NULL)
 237	return NULL;
 238    ret_bits->data = (unsigned char *)PORT_ZAlloc((hash_iter * hash_size) + 1);
 239    ret_bits->len = (hash_iter * hash_size);
 240    if(ret_bits->data == NULL) {
 241	PORT_Free(ret_bits);
 242	return NULL;
 243    }
 244
 245    /* allocate intermediate hash buffer.  8 is for the 8 bytes of
 246     * data which are added based on iteration number 
 247     */
 248
 249    if ((unsigned int)hash_size > pbe_param->salt.len) {
 250	state_len = hash_size;
 251    } else {
 252	state_len = pbe_param->salt.len;
 253    }
 254    state = (unsigned char *)PORT_ZAlloc(state_len);
 255    if(state == NULL) {
 256	rv = SECFailure;
 257	goto loser;
 258    }
 259    if(pbe_param->salt.len > 0) {
 260	PORT_Memcpy(state, pbe_param->salt.data, pbe_param->salt.len);
 261    }
 262
 263    cx = HMAC_Create(hashObj, init_hash->data, init_hash->len, PR_TRUE);
 264    if (cx == NULL) {
 265	rv = SECFailure;
 266	goto loser;
 267    }
 268
 269    for(i = 0; i < hash_iter; i++) { 
 270
 271	/* generate output bits */
 272	HMAC_Begin(cx);
 273	HMAC_Update(cx, state, state_len);
 274	HMAC_Update(cx, pbe_param->salt.data, pbe_param->salt.len);
 275	rv = HMAC_Finish(cx, ret_bits->data + (i * hash_size),
 276			 &dig_len, hash_size);
 277	if (rv != SECSuccess)
 278	    goto loser;
 279	PORT_Assert((unsigned int)hash_size == dig_len);
 280
 281	/* generate new state */
 282	HMAC_Begin(cx);
 283	HMAC_Update(cx, state, state_len);
 284	rv = HMAC_Finish(cx, state, &state_len, state_len);
 285	if (rv != SECSuccess)
 286	    goto loser;
 287	PORT_Assert(state_len == dig_len);
 288    }
 289
 290loser:
 291    if (state != NULL)
 292	PORT_ZFree(state, state_len);
 293    HMAC_Destroy(cx, PR_TRUE);
 294
 295    if(rv != SECSuccess) {
 296	SECITEM_ZfreeItem(ret_bits, PR_TRUE);
 297	ret_bits = NULL;
 298    }
 299
 300    return ret_bits;
 301}
 302
 303/* generate bits for the key and iv determination.  if enough bits
 304 * are not generated using PKCS 5, then we need to generate more bits
 305 * based on the extension proposed in PKCS 12
 306 */
 307static SECItem *
 308nsspkcs5_PBKDF1Extended(const SECHashObject *hashObj,
 309	 NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, PRBool faulty3DES)
 310{
 311    SECItem * hash 		= NULL;
 312    SECItem * newHash 		= NULL;
 313    int       bytes_needed;
 314    int       bytes_available;
 315    
 316    bytes_needed = pbe_param->ivLen + pbe_param->keyLen;
 317    bytes_available = hashObj->length;
 318    
 319    hash = nsspkcs5_PBKDF1(hashObj, &pbe_param->salt, pwitem, 
 320						pbe_param->iter, faulty3DES);
 321
 322    if(hash == NULL) {
 323	return NULL;
 324    }
 325
 326    if(bytes_needed <= bytes_available) {
 327	return hash;
 328    } 
 329
 330    newHash = nsspkcs5_PFXPBE(hashObj, pbe_param, hash, bytes_needed);
 331    if (hash != newHash)
 332	SECITEM_FreeItem(hash, PR_TRUE);
 333    return newHash;
 334}
 335
 336#ifdef PBKDF2
 337
 338/*
 339 * PBDKDF2 is PKCS #5 v2.0 it's currently not used by NSS
 340 */
 341static void
 342do_xor(unsigned char *dest, unsigned char *src, int len)
 343{
 344   /* use byt xor, not all platforms are happy about inaligned 
 345    * integer fetches */
 346    while (len--) {
 347    	*dest = *dest ^ *src;
 348	dest++;
 349	src++;
 350    }
 351}
 352
 353static SECStatus
 354nsspkcs5_PBKFD2_F(const SECHashObject *hashobj, SECItem *pwitem, SECItem *salt,
 355			int iterations, unsigned int i, unsigned char *T)
 356{
 357    int j;
 358    HMACContext *cx = NULL;
 359    unsigned int hLen = hashobj->length;
 360    SECStatus rv = SECFailure;
 361    unsigned char *last = NULL;
 362    unsigned int lastLength = salt->len + 4;
 363    unsigned int lastBufLength;
 364
 365    cx=HMAC_Create(hashobj,pwitem->data,pwitem->len,PR_FALSE);
 366    if (cx == NULL) {
 367	goto loser;
 368    }
 369    PORT_Memset(T,0,hLen);
 370    lastBufLength = PR_MAX(lastLength, hLen);
 371    last = PORT_Alloc(lastBufLength);
 372    if (last == NULL) {
 373	goto loser;
 374    }
 375    PORT_Memcpy(last,salt->data,salt->len);
 376    last[salt->len  ] = (i >> 24) & 0xff;
 377    last[salt->len+1] = (i >> 16) & 0xff;
 378    last[salt->len+2] = (i >> 8) & 0xff;
 379    last[salt->len+3] =    i  & 0xff;
 380
 381    /* NOTE: we need at least one iteration to return success! */
 382    for (j=0; j < iterations; j++) {
 383	HMAC_Begin(cx);
 384	HMAC_Update(cx,last,lastLength);
 385	rv =HMAC_Finish(cx,last,&lastLength,hLen);
 386	if (rv !=SECSuccess) {
 387	   break;
 388	}
 389	do_xor(T,last,hLen);
 390    }
 391loser:
 392    if (cx) {
 393	HMAC_Destroy(cx, PR_TRUE);
 394    }
 395    if (last) {
 396	PORT_ZFree(last,lastBufLength);
 397    }
 398    return rv;
 399}
 400
 401static SECItem *
 402nsspkcs5_PBKDF2(const SECHashObject *hashobj, NSSPKCS5PBEParameter *pbe_param, 
 403							SECItem *pwitem)
 404{
 405    int iterations = pbe_param->iter;
 406    int bytesNeeded = pbe_param->keyLen;
 407    unsigned int dkLen = bytesNeeded;
 408    unsigned int hLen = hashobj->length;
 409    unsigned int nblocks = (dkLen+hLen-1) / hLen;
 410    unsigned int i;
 411    unsigned char *rp;
 412    unsigned char *T = NULL;
 413    SECItem *result = NULL;
 414    SECItem *salt = &pbe_param->salt;
 415    SECStatus rv = SECFailure;
 416
 417    result = SECITEM_AllocItem(NULL,NULL,nblocks*hLen);
 418    if (result == NULL) {
 419	return NULL;
 420    }
 421
 422    T = PORT_Alloc(hLen);
 423    if (T == NULL) {
 424	goto loser;
 425    }
 426
 427    for (i=1,rp=result->data; i <= nblocks ; i++, rp +=hLen) {
 428	rv = nsspkcs5_PBKFD2_F(hashobj,pwitem,salt,iterations,i,T);
 429	if (rv != SECSuccess) {
 430	    break;
 431	}
 432	PORT_Memcpy(rp,T,hLen);
 433    }
 434
 435loser:
 436    if (T) {
 437	PORT_ZFree(T,hLen);
 438    }
 439    if (rv != SECSuccess) {
 440	SECITEM_FreeItem(result,PR_TRUE);
 441	result = NULL;
 442    } else {
 443	result->len = dkLen;
 444    }
 445	
 446    return result;
 447}
 448#endif
 449
 450#define HMAC_BUFFER 64
 451#define NSSPBE_ROUNDUP(x,y) ((((x)+((y)-1))/(y))*(y))
 452#define NSSPBE_MIN(x,y) ((x) < (y) ? (x) : (y))
 453/*
 454 * This is the extended PBE function defined by the final PKCS #12 spec.
 455 */
 456static SECItem *
 457nsspkcs5_PKCS12PBE(const SECHashObject *hashObject, 
 458		   NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, 
 459		   PBEBitGenID bitGenPurpose, unsigned int bytesNeeded)
 460{
 461    PRArenaPool *arena = NULL;
 462    unsigned int SLen,PLen;
 463    unsigned int hashLength = hashObject->length;
 464    unsigned char *S, *P;
 465    SECItem *A = NULL, B, D, I;
 466    SECItem *salt = &pbe_param->salt;
 467    unsigned int c,i = 0;
 468    unsigned int hashLen;
 469    int iter;
 470    unsigned char *iterBuf;
 471    void *hash = NULL;
 472
 473    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
 474    if(!arena) {
 475	return NULL;
 476    }
 477
 478    /* how many hash object lengths are needed */
 479    c = (bytesNeeded + (hashLength-1))/hashLength;
 480
 481    /* initialize our buffers */
 482    D.len = HMAC_BUFFER;
 483    /* B and D are the same length, use one alloc go get both */
 484    D.data = (unsigned char*)PORT_ArenaZAlloc(arena, D.len*2);
 485    B.len = D.len;
 486    B.data = D.data + D.len;
 487
 488    /* if all goes well, A will be returned, so don't use our temp arena */
 489    A = SECITEM_AllocItem(NULL,NULL,c*hashLength);
 490    if (A == NULL) {
 491	goto loser;
 492    }
 493    
 494    SLen = NSSPBE_ROUNDUP(salt->len,HMAC_BUFFER);
 495    PLen = NSSPBE_ROUNDUP(pwitem->len,HMAC_BUFFER);
 496    I.len = SLen+PLen;
 497    I.data = (unsigned char*)PORT_ArenaZAlloc(arena, I.len);
 498    if (I.data == NULL) {
 499	goto loser;
 500    }
 501
 502    /* S & P are only used to initialize I */
 503    S = I.data;
 504    P = S + SLen;
 505
 506    PORT_Memset(D.data, (char)bitGenPurpose, D.len);
 507    if (SLen) {
 508	for (i=0; i < SLen; i += salt->len) {
 509	    PORT_Memcpy(S+i, salt->data, NSSPBE_MIN(SLen-i,salt->len));
 510	}
 511    } 
 512    if (PLen) {
 513	for (i=0; i < PLen; i += pwitem->len) {
 514	    PORT_Memcpy(P+i, pwitem->data, NSSPBE_MIN(PLen-i,pwitem->len));
 515	}
 516    } 
 517
 518    iterBuf = (unsigned char*)PORT_ArenaZAlloc(arena,hashLength);
 519    if (iterBuf == NULL) {
 520	goto loser;
 521    }
 522
 523    hash = hashObject->create();
 524    if(!hash) {
 525	goto loser;
 526    }
 527    /* calculate the PBE now */
 528    for(i = 0; i < c; i++) {
 529	int Bidx;	/* must be signed or the for loop won't terminate */
 530	unsigned int k, j;
 531	unsigned char *Ai = A->data+i*hashLength;
 532
 533
 534	for(iter = 0; iter < pbe_param->iter; iter++) {
 535	    hashObject->begin(hash);
 536
 537	    if (iter) {
 538		hashObject->update(hash, iterBuf, hashLen);
 539	    } else {
 540		hashObject->update(hash, D.data, D.len);
 541		hashObject->update(hash, I.data, I.len); 
 542	    }
 543
 544	    hashObject->end(hash, iterBuf, &hashLen, hashObject->length);
 545	    if(hashLen != hashObject->length) {
 546		break;
 547	    }
 548	}
 549
 550	PORT_Memcpy(Ai, iterBuf, hashLength);
 551	for (Bidx = 0; Bidx < B.len; Bidx += hashLength) {
 552	    PORT_Memcpy(B.data+Bidx,iterBuf,NSSPBE_MIN(B.len-Bidx,hashLength));
 553	}
 554
 555	k = I.len/B.len;
 556	for(j = 0; j < k; j++) {
 557	    unsigned int q, carryBit;
 558	    unsigned char *Ij = I.data + j*B.len;
 559
 560	    /* (Ij = Ij+B+1) */
 561	    for (Bidx = (B.len-1), q=1, carryBit=0; Bidx >= 0; Bidx--,q=0) {
 562		q += (unsigned int)Ij[Bidx];
 563		q += (unsigned int)B.data[Bidx];
 564		q += carryBit;
 565
 566		carryBit = (q > 0xff);
 567		Ij[Bidx] = (unsigned char)(q & 0xff);
 568	    }
 569	}
 570    }
 571loser:
 572    if (hash) {
 573    	hashObject->destroy(hash, PR_TRUE);
 574    }
 575    if(arena) {
 576	PORT_FreeArena(arena, PR_TRUE);
 577    }
 578
 579    if (A) {
 580        /* if i != c, then we didn't complete the loop above and must of failed
 581         * somwhere along the way */
 582        if (i != c) {
 583	    SECITEM_ZfreeItem(A,PR_TRUE);
 584	    A = NULL;
 585        } else {
 586    	    A->len = bytesNeeded;
 587        }
 588    }
 589    
 590    return A;
 591}
 592
 593/*
 594 * generate key as per PKCS 5
 595 */
 596SECItem *
 597nsspkcs5_ComputeKeyAndIV(NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem,
 598		      SECItem *iv, PRBool faulty3DES)
 599{
 600    SECItem *hash = NULL, *key = NULL;
 601    const SECHashObject *hashObj;
 602    PRBool getIV = PR_FALSE;
 603
 604    if((pbe_param == NULL) || (pwitem == NULL)) {
 605	return NULL;
 606    }
 607
 608    key = SECITEM_AllocItem(NULL,NULL,pbe_param->keyLen);
 609    if (key == NULL) {
 610	return NULL;
 611    }
 612
 613    if (iv && (pbe_param->ivLen) && (iv->data == NULL)) {
 614	getIV = PR_TRUE;
 615    	iv->data = (unsigned char *)PORT_Alloc(pbe_param->ivLen);
 616    	if (iv->data == NULL) {
 617	    goto loser;
 618	}
 619	iv->len = pbe_param->ivLen;
 620    }
 621
 622    hashObj = HASH_GetRawHashObject(pbe_param->hashType);
 623    switch (pbe_param->pbeType) {
 624    case NSSPKCS5_PBKDF1:
 625	hash = nsspkcs5_PBKDF1Extended(hashObj,pbe_param,pwitem,faulty3DES);
 626	if (hash == NULL) {
 627	    goto loser;
 628	}
 629	PORT_Assert(hash->len >= key->len+(getIV ? iv->len : 0));
 630	if (getIV) {
 631	    PORT_Memcpy(iv->data, hash->data+(hash->len - iv->len),iv->len);
 632	} 
 633	
 634    	break;
 635#ifdef PBKDF2
 636    case NSSPKCS5_PBKDF2:
 637	hash = nsspkcs5_PBKDF2(hashObj,pbe_param,pwitem);
 638	if (getIV) {
 639	    PORT_Memcpy(iv->data, pbe_param->ivData, iv->len);
 640	}
 641    	break;
 642#endif
 643    case NSSPKCS5_PKCS12_V2:
 644	if (getIV) {
 645	    hash = nsspkcs5_PKCS12PBE(hashObj,pbe_param,pwitem,
 646						pbeBitGenCipherIV,iv->len);
 647	    if (hash == NULL) {
 648		goto loser;
 649	    }
 650	    PORT_Memcpy(iv->data,hash->data,iv->len);
 651	    SECITEM_ZfreeItem(hash,PR_TRUE);
 652	    hash = NULL;
 653	}
 654	hash = nsspkcs5_PKCS12PBE(hashObj,pbe_param,pwitem,
 655						pbe_param->keyID,key->len);
 656    default:
 657	break;
 658    }
 659
 660    if (hash == NULL) {
 661	goto loser;
 662    }
 663
 664    if (pbe_param->is2KeyDES) {
 665	PORT_Memcpy(key->data, hash->data, (key->len * 2) / 3);
 666	PORT_Memcpy(&(key->data[(key->len  * 2) / 3]), key->data,
 667		    key->len / 3);
 668    } else {
 669	PORT_Memcpy(key->data, hash->data, key->len);
 670    }
 671
 672    SECITEM_ZfreeItem(hash, PR_TRUE);
 673    return key;
 674
 675loser:
 676    if (getIV && iv->data) {
 677	PORT_ZFree(iv->data,iv->len);
 678	iv->data = NULL;
 679    }
 680
 681    SECITEM_ZfreeItem(key, PR_TRUE);
 682    return NULL;
 683}
 684
 685static SECStatus
 686nsspkcs5_FillInParam(SECOidTag algorithm, NSSPKCS5PBEParameter *pbe_param)
 687{
 688    PRBool skipType = PR_FALSE;
 689
 690    pbe_param->keyLen = 5;
 691    pbe_param->ivLen = 8;
 692    pbe_param->hashType = HASH_AlgSHA1;
 693    pbe_param->pbeType = NSSPKCS5_PBKDF1;
 694    pbe_param->encAlg = SEC_OID_RC2_CBC;
 695    pbe_param->is2KeyDES = PR_FALSE;
 696    switch(algorithm) {
 697    /* DES3 Algorithms */
 698    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_2KEY_TRIPLE_DES_CBC:
 699	pbe_param->is2KeyDES = PR_TRUE;
 700	/* fall through */
 701    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC:
 702	pbe_param->pbeType = NSSPKCS5_PKCS12_V2;
 703	/* fall through */
 704    case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_TRIPLE_DES_CBC:
 705	pbe_param->keyLen = 24;
 706	pbe_param->encAlg = SEC_OID_DES_EDE3_CBC;
 707	break;
 708
 709    /* DES Algorithms */
 710    case SEC_OID_PKCS5_PBE_WITH_MD2_AND_DES_CBC:
 711    	pbe_param->hashType = HASH_AlgMD2;
 712	goto finish_des;
 713    case SEC_OID_PKCS5_PBE_WITH_MD5_AND_DES_CBC:
 714    	pbe_param->hashType = HASH_AlgMD5;
 715	/* fall through */
 716    case SEC_OID_PKCS5_PBE_WITH_SHA1_AND_DES_CBC:
 717finish_des:
 718	pbe_param->keyLen = 8;
 719	pbe_param->encAlg =  SEC_OID_DES_CBC;
 720	break;
 721
 722    /* RC2 Algorithms */
 723    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC2_CBC:
 724	pbe_param->keyLen = 16;
 725	/* fall through */
 726    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC:
 727	pbe_param->pbeType = NSSPKCS5_PKCS12_V2;
 728	break;
 729    case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_128_BIT_RC2_CBC:
 730	pbe_param->keyLen = 16;
 731	/* fall through */
 732    case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC:
 733	break;
 734
 735    /* RC4 algorithms */
 736    case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_128_BIT_RC4:
 737	skipType = PR_TRUE;
 738	/* fall through */
 739    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC4:
 740	pbe_param->keyLen = 16;
 741	/* fall through */
 742    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC4:
 743	if (!skipType) {
 744    	    pbe_param->pbeType = NSSPKCS5_PKCS12_V2;
 745	}
 746	/* fall through */
 747    case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_40_BIT_RC4:
 748        pbe_param->ivLen = 0;
 749        pbe_param->encAlg =  SEC_OID_RC4;
 750        break;
 751
 752#ifdef PBKDF2
 753    case SEC_OID_PKCS5_PBKDF2:
 754    case SEC_OID_PKCS5_PBES2:
 755    case SEC_OID_PKCS5_PBMAC1:
 756	/* everything else will be filled in by the template */
 757        pbe_param->ivLen = 0;
 758	pbe_param->pbeType = NSSPKCS5_PBKDF2;
 759        pbe_param->encAlg =  SEC_OID_PKCS5_PBKDF2;
 760	pbe_param->keyLen = 0; /* needs to be set by caller after return */
 761	break;
 762#endif
 763
 764    default:
 765        return SECFailure;
 766    }
 767
 768    return SECSuccess;
 769}
 770
 771/* decode the algid and generate a PKCS 5 parameter from it
 772 */
 773NSSPKCS5PBEParameter *
 774nsspkcs5_NewParam(SECOidTag alg, SECItem *salt, int iterator)
 775{
 776    PRArenaPool *arena = NULL;
 777    NSSPKCS5PBEParameter *pbe_param = NULL;
 778    SECStatus rv = SECFailure;
 779
 780    arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
 781    if (arena == NULL)
 782	return NULL;
 783
 784    /* allocate memory for the parameter */
 785    pbe_param = (NSSPKCS5PBEParameter *)PORT_ArenaZAlloc(arena, 
 786	sizeof(NSSPKCS5PBEParameter));
 787
 788    if (pbe_param == NULL) {
 789	goto loser;
 790    }
 791
 792    pbe_param->poolp = arena;
 793
 794    rv = nsspkcs5_FillInParam(alg, pbe_param);
 795    if (rv != SECSuccess) {
 796	goto loser;
 797    }
 798
 799    pbe_param->iter = iterator;
 800    if (salt) {
 801	rv = SECITEM_CopyItem(arena,&pbe_param->salt,salt);
 802    }
 803
 804    /* default key gen */
 805    pbe_param->keyID = pbeBitGenCipherKey;
 806
 807loser:
 808    if (rv != SECSuccess) {
 809	PORT_FreeArena(arena, PR_TRUE);
 810	pbe_param = NULL;
 811    }
 812
 813    return pbe_param;
 814}
 815
 816/*
 817 * find the hash type needed to implement a specific HMAC.
 818 * OID definitions are from pkcs 5 v2.0 and 2.1
 819 */
 820HASH_HashType
 821HASH_FromHMACOid(SECOidTag hmac)
 822{
 823    switch (hmac) {
 824    case SEC_OID_HMAC_SHA1:
 825    	return HASH_AlgSHA1;
 826    case SEC_OID_HMAC_SHA256:
 827    	return HASH_AlgSHA256;
 828    case SEC_OID_HMAC_SHA384:
 829    	return HASH_AlgSHA384;
 830    case SEC_OID_HMAC_SHA512:
 831    	return HASH_AlgSHA512;
 832    case SEC_OID_HMAC_SHA224:
 833    default:
 834	break;
 835    }
 836    return HASH_AlgNULL;
 837}
 838
 839/* decode the algid and generate a PKCS 5 parameter from it
 840 */
 841NSSPKCS5PBEParameter *
 842nsspkcs5_AlgidToParam(SECAlgorithmID *algid)
 843{
 844    NSSPKCS5PBEParameter *pbe_param = NULL;
 845    nsspkcs5V2PBEParameter pbev2_param;
 846    SECOidTag algorithm;
 847    SECStatus rv = SECFailure;
 848
 849    if (algid == NULL) {
 850	return NULL;
 851    }
 852
 853    algorithm = SECOID_GetAlgorithmTag(algid);
 854    if (algorithm == SEC_OID_UNKNOWN) {
 855	goto loser;
 856    }
 857
 858    pbe_param = nsspkcs5_NewParam(algorithm, NULL, 1);
 859    if (pbe_param == NULL) {
 860	goto loser;
 861    }
 862
 863    /* decode parameter */
 864    rv = SECFailure;
 865    switch (pbe_param->pbeType) {
 866    case NSSPKCS5_PBKDF1:
 867	rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, 
 868	    NSSPKCS5PBEParameterTemplate, &algid->parameters);
 869	break;
 870    case NSSPKCS5_PKCS12_V2:
 871	rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, 
 872		NSSPKCS5PKCS12V2PBEParameterTemplate, &algid->parameters);
 873	break;
 874#ifdef PBKDF2
 875    case NSSPKCS5_PBKDF2:
 876	PORT_Memset(&pbev2_param,0, sizeof(pbev2_param));
 877	/* just the PBE */
 878	if (algorithm == SEC_OID_PKCS5_PBKDF2) {
 879	    rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param,
 880		NSSPKCS5V2PBEParameterTemplate, &algid->parameters);
 881	} else {
 882	    /* PBE data an others */
 883	    rv = SEC_ASN1DecodeItem(pbe_param->poolp, &pbev2_param, 
 884		NSSPKCS5V2PBES2ParameterTemplate, &algid->parameters);
 885	    if (rv != SECSuccess) {
 886		break;
 887	    }
 888            pbe_param->encAlg = SECOID_GetAlgorithmTag(&pbev2_param.algParams);
 889	    rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param,
 890		NSSPKCS5V2PBEParameterTemplate, 
 891		&pbev2_param.keyParams.parameters);
 892	    if (rv != SECSuccess) {
 893		break;
 894	    }
 895    	    pbe_param->keyLen = DER_GetInteger(&pbe_param->keyLength);
 896	}
 897	/* we we are encrypting, save any iv's */
 898	if (algorithm == SEC_OID_PKCS5_PBES2) {
 899	    pbe_param->ivLen = pbev2_param.algParams.parameters.len;
 900	    pbe_param->ivData = pbev2_param.algParams.parameters.data;
 901	}
 902	pbe_param->hashType = 
 903	    HASH_FromHMACOid(SECOID_GetAlgorithmTag(&pbe_param->prfAlg));
 904	if (pbe_param->hashType == HASH_AlgNULL) {
 905	    PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
 906	    rv = SECFailure;
 907	}
 908	break;
 909#endif
 910    }
 911
 912loser:
 913    if (rv == SECSuccess) {
 914    	pbe_param->iter = DER_GetInteger(&pbe_param->iteration);
 915    } else {
 916	nsspkcs5_DestroyPBEParameter(pbe_param);
 917	pbe_param = NULL;
 918    }
 919
 920    return pbe_param;
 921}
 922
 923/* destroy a pbe parameter.  it assumes that the parameter was 
 924 * generated using the appropriate create function and therefor
 925 * contains an arena pool.
 926 */
 927void 
 928nsspkcs5_DestroyPBEParameter(NSSPKCS5PBEParameter *pbe_param)
 929{
 930    if (pbe_param != NULL) {
 931	PORT_FreeArena(pbe_param->poolp, PR_FALSE);
 932    }
 933}
 934
 935
 936/* crypto routines */
 937/* perform DES encryption and decryption.  these routines are called
 938 * by nsspkcs5_CipherData.  In the case of an error, NULL is returned.
 939 */
 940static SECItem *
 941sec_pkcs5_des(SECItem *key, SECItem *iv, SECItem *src, PRBool triple_des, 
 942								PRBool encrypt)
 943{
 944    SECItem *dest;
 945    SECItem *dup_src;
 946    SECStatus rv = SECFailure;
 947    int pad;
 948
 949    if((src == NULL) || (key == NULL) || (iv == NULL))
 950	return NULL;
 951
 952    dup_src = SECITEM_DupItem(src);
 953    if(dup_src == NULL) {
 954	return NULL;
 955    }
 956
 957    if(encrypt != PR_FALSE) {
 958	void *dummy;
 959
 960	dummy = CBC_PadBuffer(NULL, dup_src->data, 
 961	    dup_src->len, &dup_src->len, 8 /* DES_BLOCK_SIZE */);
 962	if(dummy == NULL) {
 963	    SECITEM_FreeItem(dup_src, PR_TRUE);
 964	    return NULL;
 965	}
 966	dup_src->data = (unsigned char*)dummy;
 967    }
 968
 969    dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem));
 970    if(dest != NULL) {
 971	/* allocate with over flow */
 972	dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64);
 973	if(dest->data != NULL) {
 974	    DESContext *ctxt;
 975	    ctxt = DES_CreateContext(key->data, iv->data, 
 976			(triple_des ? NSS_DES_EDE3_CBC : NSS_DES_CBC), 
 977			encrypt);
 978	
 979	    if(ctxt != NULL) {
 980		rv = (encrypt ? DES_Encrypt : DES_Decrypt)(
 981			ctxt, dest->data, &dest->len,
 982			dup_src->len + 64, dup_src->data, dup_src->len);
 983
 984		/* remove padding -- assumes 64 bit blocks */
 985		if((encrypt == PR_FALSE) && (rv == SECSuccess)) {
 986		    pad = dest->data[dest->len-1];
 987		    if((pad > 0) && (pad <= 8)) {
 988			if(dest->data[dest->len-pad] != pad) {
 989			    rv = SECFailure;
 990			    PORT_SetError(SEC_ERROR_BAD_PASSWORD);
 991			} else {
 992			    dest->len -= pad;
 993			}
 994		    } else {
 995			rv = SECFailure;
 996			PORT_SetError(SEC_ERROR_BAD_PASSWORD);
 997		    }
 998		}
 999		DES_DestroyContext(ctxt, PR_TRUE);
1000	    }
1001	}
1002    }
1003
1004    if(rv == SECFailure) {
1005	if(dest != NULL) {
1006	    SECITEM_FreeItem(dest, PR_TRUE);
1007	}
1008	dest = NULL;
1009    }
1010
1011    if(dup_src != NULL) {
1012	SECITEM_FreeItem(dup_src, PR_TRUE);
1013    }
1014
1015    return dest;
1016}
1017
1018/* perform aes encryption/decryption if an error occurs, NULL is returned
1019 */
1020static SECItem *
1021sec_pkcs5_aes(SECItem *key, SECItem *iv, SECItem *src, PRBool triple_des, 
1022								PRBool encrypt)
1023{
1024    SECItem *dest;
1025    SECItem *dup_src;
1026    SECStatus rv = SECFailure;
1027    int pad;
1028
1029    if((src == NULL) || (key == NULL) || (iv == NULL))
1030	return NULL;
1031
1032    dup_src = SECITEM_DupItem(src);
1033    if(dup_src == NULL) {
1034	return NULL;
1035    }
1036
1037    if(encrypt != PR_FALSE) {
1038	void *dummy;
1039
1040	dummy = CBC_PadBuffer(NULL, dup_src->data, 
1041	    dup_src->len, &dup_src->len,AES_BLOCK_SIZE);
1042	if(dummy == NULL) {
1043	    SECITEM_FreeItem(dup_src, PR_TRUE);
1044	    return NULL;
1045	}
1046	dup_src->data = (unsigned char*)dummy;
1047    }
1048
1049    dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem));
1050    if(dest != NULL) {
1051	/* allocate with over flow */
1052	dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64);
1053	if(dest->data != NULL) {
1054	    AESContext *ctxt;
1055	    ctxt = AES_CreateContext(key->data, iv->data, 
1056			NSS_AES_CBC, encrypt, key->len, 16);
1057	
1058	    if(ctxt != NULL) {
1059		rv = (encrypt ? AES_Encrypt : AES_Decrypt)(
1060			ctxt, dest->data, &dest->len,
1061			dup_src->len + 64, dup_src->data, dup_src->len);
1062
1063		/* remove padding -- assumes 64 bit blocks */
1064		if((encrypt == PR_FALSE) && (rv == SECSuccess)) {
1065		    pad = dest->data[dest->len-1];
1066		    if((pad > 0) && (pad <= 16)) {
1067			if(dest->data[dest->len-pad] != pad) {
1068			    rv = SECFailure;
1069			    PORT_SetError(SEC_ERROR_BAD_PASSWORD);
1070			} else {
1071			    dest->len -= pad;
1072			}
1073		    } else {
1074			rv = SECFailure;
1075			PORT_SetError(SEC_ERROR_BAD_PASSWORD);
1076		    }
1077		}
1078		AES_DestroyContext(ctxt, PR_TRUE);
1079	    }
1080	}
1081    }
1082
1083    if(rv == SECFailure) {
1084	if(dest != NULL) {
1085	    SECITEM_FreeItem(dest, PR_TRUE);
1086	}
1087	dest = NULL;
1088    }
1089
1090    if(dup_src != NULL) {
1091	SECITEM_FreeItem(dup_src, PR_TRUE);
1092    }
1093
1094    return dest;
1095}
1096
1097/* perform rc2 encryption/decryption if an error occurs, NULL is returned
1098 */
1099static SECItem *
1100sec_pkcs5_rc2(SECItem *key, SECItem *iv, SECItem *src, PRBool dummy, 
1101								PRBool encrypt)
1102{
1103    SECItem *dest;
1104    SECItem *dup_src;
1105    SECStatus rv = SECFailure;
1106    int pad;
1107
1108    if((src == NULL) || (key == NULL) || (iv == NULL)) {
1109	return NULL;
1110    }
1111
1112    dup_src = SECITEM_DupItem(src);
1113    if(dup_src == NULL) {
1114	return NULL;
1115    }
1116
1117    if(encrypt != PR_FALSE) {
1118	void *dummy;
1119
1120	dummy = CBC_PadBuffer(NULL, dup_src->data, 
1121		      dup_src->len, &dup_src->len, 8 /* RC2_BLOCK_SIZE */);
1122	if(dummy == NULL) {
1123	    SECITEM_FreeItem(dup_src, PR_TRUE);
1124	    return NULL;
1125	}
1126	dup_src->data = (unsigned char*)dummy;
1127    }
1128
1129    dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem));
1130    if(dest != NULL) {
1131	dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64);
1132	if(dest->data != NULL) {
1133	    RC2Context *ctxt;
1134
1135	    ctxt = RC2_CreateContext(key->data, key->len, iv->data,
1136					 	NSS_RC2_CBC, key->len);
1137
1138	    if(ctxt != NULL) {
1139		rv = (encrypt ? RC2_Encrypt: RC2_Decrypt)(
1140			ctxt, dest->data, &dest->len,
1141			dup_src->len + 64, dup_src->data, dup_src->len);
1142
1143		/* assumes 8 byte blocks  -- remove padding */	
1144		if((rv == SECSuccess) && (encrypt != PR_TRUE)) {
1145		    pad = dest->data[dest->len-1];
1146		    if((pad > 0) && (pad <= 8)) {
1147			if(dest->data[dest->len-pad] != pad) {
1148			    PORT_SetError(SEC_ERROR_BAD_PASSWORD);
1149			    rv = SECFailure;
1150			} else {
1151			    dest->len -= pad;
1152			}
1153		    } else {
1154			PORT_SetError(SEC_ERROR_BAD_PASSWORD);
1155			rv = SECFailure;
1156		    }
1157		}
1158
1159	    }
1160	}
1161    }
1162
1163    if((rv != SECSuccess) && (dest != NULL)) {
1164	SECITEM_FreeItem(dest, PR_TRUE);
1165	dest = NULL;
1166    }
1167
1168    if(dup_src != NULL) {
1169	SECITEM_FreeItem(dup_src, PR_TRUE);
1170    }
1171
1172    return dest;
1173}
1174
1175/* perform rc4 encryption and decryption */
1176static SECItem *
1177sec_pkcs5_rc4(SECItem *key, SECItem *iv, SECItem *src, PRBool dummy_op,
1178								 PRBool encrypt)
1179{
1180    SECItem *dest;
1181    SECStatus rv = SECFailure;
1182
1183    if((src == NULL) || (key == NULL) || (iv == NULL)) {
1184	return NULL;
1185    }
1186
1187    dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem));
1188    if(dest != NULL) {
1189	dest->data = (unsigned char *)PORT_ZAlloc(sizeof(unsigned char) *
1190	    (src->len + 64));
1191	if(dest->data != NULL) {
1192	    RC4Context *ctxt;
1193
1194	    ctxt = RC4_CreateContext(key->data, key->len);
1195	    if(ctxt) { 
1196		rv = (encrypt ? RC4_Encrypt : RC4_Decrypt)(
1197				ctxt, dest->data, &dest->len,
1198				src->len + 64, src->data, src->len);
1199		RC4_DestroyContext(ctxt, PR_TRUE);
1200	    }
1201	}
1202    }
1203
1204    if((rv != SECSuccess) && (dest)) {
1205	SECITEM_FreeItem(dest, PR_TRUE);
1206	dest = NULL;
1207    }
1208
1209    return dest;
1210}
1211/* function pointer template for crypto functions */
1212typedef SECItem *(* pkcs5_crypto_func)(SECItem *key, SECItem *iv,
1213                                         SECItem *src, PRBool op1, PRBool op2);
1214
1215/* performs the cipher operation on the src and returns the result.
1216 * if an error occurs, NULL is returned. 
1217 *
1218 * a null length password is allowed.  this corresponds to encrypting
1219 * the data with ust the salt.
1220 */
1221/* change this to use PKCS 11? */
1222SECItem *
1223nsspkcs5_CipherData(NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, 
1224		    SECItem *src, PRBool encrypt, PRBool *update)
1225{
1226    SECItem *key = NULL, iv;
1227    SECItem *dest = NULL;
1228    PRBool tripleDES = PR_TRUE;
1229    pkcs5_crypto_func cryptof;
1230
1231    iv.data = NULL;
1232
1233    if (update) { 
1234        *update = PR_FALSE;
1235    }
1236
1237    if ((pwitem == NULL) || (src == NULL)) {
1238	return NULL;
1239    }
1240
1241    /* get key, and iv */
1242    key = nsspkcs5_ComputeKeyAndIV(pbe_param, pwitem, &iv, PR_FALSE);
1243    if(key == NULL) {
1244	return NULL;
1245    }
1246
1247    switch(pbe_param->encAlg) {
1248    /* PKCS 5 v2 only */
1249    case SEC_OID_AES_128_CBC:
1250    case SEC_OID_AES_192_CBC:
1251    case SEC_OID_AES_256_CBC:
1252	cryptof = sec_pkcs5_aes;
1253	break;
1254    case SEC_OID_DES_EDE3_CBC:
1255	cryptof = sec_pkcs5_des;
1256	tripleDES = PR_TRUE;
1257	break;
1258    case SEC_OID_DES_CBC:
1259	cryptof = sec_pkcs5_des;
1260	tripleDES = PR_FALSE;
1261	break;
1262    case SEC_OID_RC2_CBC:
1263	cryptof = sec_pkcs5_rc2;
1264	break;
1265    case SEC_OID_RC4:
1266	cryptof = sec_pkcs5_rc4;
1267	break;
1268    default:
1269	cryptof = NULL;
1270	break;
1271    }
1272
1273    if (cryptof == NULL) {
1274	goto loser;
1275    }
1276
1277    dest = (*cryptof)(key, &iv, src, tripleDES, encrypt);
1278    /* 
1279     * it's possible for some keys and keydb's to claim to
1280     * be triple des when they're really des. In this case
1281     * we simply try des. If des works we set the update flag
1282     * so the key db knows it needs to update all it's entries.
1283     *  The case can only happen on decrypted of a 
1284     *  SEC_OID_DES_EDE3_CBD.
1285     */
1286    if ((dest == NULL) && (encrypt == PR_FALSE) && 
1287				(pbe_param->encAlg == SEC_OID_DES_EDE3_CBC)) {
1288	dest = (*cryptof)(key, &iv, src, PR_FALSE, encrypt);
1289	if (update && (dest != NULL)) *update = PR_TRUE;
1290    }
1291
1292loser:
1293    if (key != NULL) {
1294	SECITEM_ZfreeItem(key, PR_TRUE);
1295    }
1296    if (iv.data != NULL) {
1297	SECITEM_ZfreeItem(&iv, PR_FALSE);
1298    }
1299
1300    return dest;
1301}
1302
1303/* creates a algorithm ID containing the PBE algorithm and appropriate
1304 * parameters.  the required parameter is the algorithm.  if salt is
1305 * not specified, it is generated randomly.  if IV is specified, it overrides
1306 * the PKCS 5 generation of the IV.  
1307 *
1308 * the returned SECAlgorithmID should be destroyed using 
1309 * SECOID_DestroyAlgorithmID
1310 */
1311SECAlgorithmID *
1312nsspkcs5_CreateAlgorithmID(PRArenaPool *arena, SECOidTag algorithm, 
1313					NSSPKCS5PBEParameter *pbe_param)
1314{
1315    SECAlgorithmID *algid, *ret_algid = NULL;
1316    SECItem der_param;
1317    nsspkcs5V2PBEParameter pkcs5v2_param;
1318
1319    SECStatus rv = SECFailure;
1320    void *dummy = NULL;
1321
1322    if (arena == NULL) {
1323	return NULL;
1324    }
1325
1326    der_param.data = NULL;
1327    der_param.len = 0;
1328
1329    /* generate the algorithm id */
1330    algid = (SECAlgorithmID *)PORT_ArenaZAlloc(arena, sizeof(SECAlgorithmID));
1331    if (algid == NULL) {
1332	goto loser;
1333    }
1334
1335    if (pbe_param->iteration.data == NULL) {
1336	dummy = SEC_ASN1EncodeInteger(pbe_param->poolp,&pbe_param->iteration,
1337								pbe_param->iter);
1338	if (dummy == NULL) {
1339	    goto loser;
1340	}
1341    }
1342    switch (pbe_param->pbeType) {
1343    case NSSPKCS5_PBKDF1:
1344	dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param,
1345					NSSPKCS5PBEParameterTemplate);
1346	break;
1347    case NSSPKCS5_PKCS12_V2:
1348	dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param,
1349	    				NSSPKCS5PKCS12V2PBEParameterTemplate);
1350	break;
1351#ifdef PBKDF2
1352    case NSSPKCS5_PBKDF2:
1353        if (pbe_param->keyLength.data == NULL) {
1354	    dummy = SEC_ASN1EncodeInteger(pbe_param->poolp,
1355				&pbe_param->keyLength, pbe_param->keyLen);
1356	    if (dummy == NULL) {
1357		goto loser;
1358	    }
1359	}
1360	PORT_Memset(&pkcs5v2_param, 0, sizeof(pkcs5v2_param));
1361	dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param,
1362	    				NSSPKCS5V2PBEParameterTemplate);
1363	if (dummy == NULL) {
1364	    break;
1365	}
1366	dummy = NULL;
1367	rv = SECOID_SetAlgorithmID(arena, &pkcs5v2_param.keyParams, 
1368				  SEC_OID_PKCS5_PBKDF2, &der_param);
1369	if (rv != SECSuccess) {
1370	    break;
1371	}
1372	der_param.data = pbe_param->ivData;
1373	der_param.len = pbe_param->ivLen;
1374	rv = SECOID_SetAlgorithmID(arena, &pkcs5v2_param.algParams, 
1375		pbe_param->encAlg, pbe_param->ivLen ? &der_param : NULL);
1376	if (rv != SECSuccess) {
1377	    break;
1378	}
1379	dummy = SEC_ASN1EncodeItem(arena,  &der_param, &pkcs5v2_param,
1380	    				NSSPKCS5V2PBES2ParameterTemplate);
1381	break;
1382#endif
1383    default:
1384	break;
1385    }
1386
1387    if (dummy == NULL) {
1388	goto loser;
1389    }
1390	
1391    rv = SECOID_SetAlgorithmID(arena, algid, algorithm, &der_param);
1392    if (rv != SECSuccess) {
1393	goto loser;
1394    }
1395
1396    ret_algid = (SECAlgorithmID *)PORT_ZAlloc(sizeof(SECAlgorithmID));
1397    if (ret_algid == NULL) {
1398	goto loser;
1399    }
1400
1401    rv = SECOID_CopyAlgorithmID(NULL, ret_algid, algid);
1402    if (rv != SECSuccess) {
1403	SECOID_DestroyAlgorithmID(ret_algid, PR_TRUE);
1404	ret_algid = NULL;
1405    }
1406
1407loser:	
1408
1409    return ret_algid;
1410}