2 * The contents of this file are subject to the Mozilla Public
3 * License Version 1.1 (the "License"); you may not use this file
4 * except in compliance with the License. You may obtain a copy of
5 * the License at http://www.mozilla.org/MPL/
7 * Software distributed under the License is distributed on an "AS
8 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
9 * implied. See the License for the specific language governing
10 * rights and limitations under the License.
12 * The Original Code is the Netscape security libraries.
14 * The Initial Developer of the Original Code is Netscape
15 * Communications Corporation. Portions created by Netscape are
16 * Copyright (C) 1994-2000 Netscape Communications Corporation. All
21 * Alternatively, the contents of this file may be used under the
22 * terms of the GNU General Public License Version 2 or later (the
23 * "GPL"), in which case the provisions of the GPL are applicable
24 * instead of those above. If you wish to allow use of your
25 * version of this file only under the terms of the GPL and not to
26 * allow others to use your version of this file under the MPL,
27 * indicate your decision by deleting the provisions above and
28 * replace them with the notice and other provisions required by
29 * the GPL. If you do not delete the provisions above, a recipient
30 * may use your version of this file under either the MPL or the
35 * Encryption/decryption routines for CMS implementation, none of which are exported.
43 #include <security_asn1/secerr.h>
44 #include <security_asn1/secasn1.h>
45 #include <security_asn1/secport.h>
47 #include <Security/SecAsn1Templates.h>
49 #include <Security/cssmapi.h>
50 #include <Security/cssmapple.h>
51 #include <Security/SecKeyPriv.h>
53 #include <Security/SecRandom.h>
54 #include <CommonCrypto/CommonCryptor.h>
58 * -------------------------------------------------------------------
63 typedef OSStatus (*nss_cms_cipher_function
) (void *, unsigned char *, unsigned int *,
64 unsigned int, const unsigned char *, unsigned int);
65 typedef OSStatus (*nss_cms_cipher_destroy
) (void *, Boolean
);
68 #define BLOCK_SIZE 4096
70 struct SecCmsCipherContextStr
{
72 void * cc
; /* CSP CONTEXT */
73 Boolean encrypt
; /* encrypt / decrypt switch */
74 int block_size
; /* block & pad sizes for cipher */
76 void * cx
; /* PK11 cipher context */
77 nss_cms_cipher_function doit
;
78 nss_cms_cipher_destroy destroy
;
79 Boolean encrypt
; /* encrypt / decrypt switch */
81 int pending_count
; /* pending data (not yet en/decrypted */
82 unsigned char pending_buf
[BLOCK_SIZE
];/* because of blocking */
86 typedef struct sec_rc2cbcParameterStr
{
87 SecAsn1Item rc2ParameterVersion
;
89 } sec_rc2cbcParameter
;
91 __unused
static const SecAsn1Template sec_rc2cbc_parameter_template
[] = {
93 0, NULL
, sizeof(sec_rc2cbcParameter
) },
94 { SEC_ASN1_INTEGER
| SEC_ASN1_SIGNED_INT
,
95 offsetof(sec_rc2cbcParameter
,rc2ParameterVersion
) },
96 { SEC_ASN1_OCTET_STRING
,
97 offsetof(sec_rc2cbcParameter
,iv
) },
101 // TODO: get rid of this?
104 ** Convert a der encoded *signed* integer into a machine integral value.
105 ** If an underflow/overflow occurs, sets error code and returns min/max.
108 DER_GetInteger(SecAsn1Item
*it
)
111 unsigned len
= it
->Length
;
112 unsigned char *cp
= it
->Data
;
113 unsigned long overflow
= 0x1ffUL
<< (((sizeof(ival
) - 1) * 8) - 1);
114 unsigned long ofloinit
;
118 ofloinit
= ival
& overflow
;
121 if ((ival
& overflow
) != ofloinit
) {
122 PORT_SetError(SEC_ERROR_BAD_DER
);
135 /* S/MIME picked id values to represent differnt keysizes */
136 /* I do have a formula, but it ain't pretty, and it only works because you
137 * can always match three points to a parabola:) */
138 static unsigned char rc2_map(SecAsn1Item
*version
)
142 x
= DER_GetInteger(version
);
152 static unsigned long rc2_unmap(unsigned long x
)
161 #endif /* USE_CDSA_CRYPTO */
163 /* default IV size in bytes */
164 #define DEFAULT_IV_SIZE 8
165 /* IV/block size for AES */
166 #define AES_BLOCK_SIZE 16
167 /* max IV size in bytes */
168 #define MAX_IV_SIZE AES_BLOCK_SIZE
171 #ifndef kCCKeySizeMaxRC2
172 #define kCCKeySizeMaxRC2 16
174 #ifndef kCCBlockSizeRC2
175 #define kCCBlockSizeRC2 8
179 static SecCmsCipherContextRef
180 SecCmsCipherContextStart(PRArenaPool
*poolp
, SecSymmetricKeyRef key
, SECAlgorithmID
*algid
, Boolean encrypt
)
182 SecCmsCipherContextRef cc
;
186 uint8_t ivbuf
[MAX_IV_SIZE
];
187 SecAsn1Item initVector
= { DEFAULT_IV_SIZE
, ivbuf
};
189 CSSM_CC_HANDLE ciphercc
= 0;
190 CSSM_ALGORITHMS algorithm
;
191 CSSM_PADDING padding
= CSSM_PADDING_PKCS7
;
192 CSSM_ENCRYPT_MODE mode
;
193 CSSM_CSP_HANDLE cspHandle
;
194 const CSSM_KEY
*cssmKey
;
195 //CSSM_CONTEXT_ATTRIBUTE contextAttribute = { CSSM_ATTRIBUTE_ALG_PARAMS, sizeof(SecAsn1Item *) };
197 CCCryptorRef ciphercc
= NULL
;
198 CCOptions cipheroptions
= kCCOptionPKCS7Padding
;
199 int cipher_blocksize
= 0;
203 rv
= SecKeyGetCSPHandle(key
, &cspHandle
);
206 rv
= SecKeyGetCSSMKey(key
, &cssmKey
);
211 // @@@ Add support for PBE based stuff
213 oidData
= SECOID_FindOID(&algid
->algorithm
);
216 algtag
= oidData
->offset
;
218 algorithm
= oidData
->cssmAlgorithm
;
224 case SEC_OID_RC2_CBC
:
226 case SEC_OID_DES_EDE3_CBC
:
227 case SEC_OID_DES_EDE
:
228 case SEC_OID_DES_CBC
:
229 case SEC_OID_RC5_CBC_PAD
:
230 case SEC_OID_FORTEZZA_SKIPJACK
:
231 mode
= CSSM_ALGMODE_CBCPadIV8
;
234 /* RFC 3565 says that these sizes refer to key size, NOT block size */
235 case SEC_OID_AES_128_CBC
:
236 case SEC_OID_AES_192_CBC
:
237 case SEC_OID_AES_256_CBC
:
238 initVector
.Length
= AES_BLOCK_SIZE
;
239 mode
= CSSM_ALGMODE_CBCPadIV8
;
242 case SEC_OID_DES_ECB
:
243 case SEC_OID_AES_128_ECB
:
244 case SEC_OID_AES_192_ECB
:
245 case SEC_OID_AES_256_ECB
:
246 mode
= CSSM_ALGMODE_ECBPad
;
249 case SEC_OID_DES_OFB
:
250 mode
= CSSM_ALGMODE_OFBPadIV8
;
253 case SEC_OID_DES_CFB
:
254 mode
= CSSM_ALGMODE_CFBPadIV8
;
261 CCAlgorithm alg
= -1;
263 case SEC_OID_DES_CBC
:
264 alg
= kCCAlgorithmDES
;
265 cipher_blocksize
= kCCBlockSizeDES
;
267 case SEC_OID_DES_EDE3_CBC
:
268 alg
= kCCAlgorithm3DES
;
269 cipher_blocksize
= kCCBlockSize3DES
;
271 case SEC_OID_RC2_CBC
:
272 alg
= kCCAlgorithmRC2
;
273 cipher_blocksize
= kCCBlockSizeRC2
;
275 case SEC_OID_AES_128_CBC
:
276 case SEC_OID_AES_192_CBC
:
277 case SEC_OID_AES_256_CBC
:
278 alg
= kCCAlgorithmAES128
;
279 cipher_blocksize
= kCCBlockSizeAES128
;
280 initVector
.Length
= AES_BLOCK_SIZE
;
290 CSSM_CC_HANDLE randomcc
;
291 //SecAsn1Item *parameters;
293 // Generate random initVector
294 if (CSSM_CSP_CreateRandomGenContext(cspHandle
,
295 CSSM_ALGID_APPLE_YARROW
,
301 if (CSSM_GenerateRandom(randomcc
, &initVector
))
303 CSSM_DeleteContext(randomcc
);
305 if (SecRandomCopyBytes(kSecRandomDefault
,
306 initVector
.Length
, initVector
.Data
))
310 // Put IV into algid.parameters
314 case SEC_OID_DES_EDE3_CBC
:
315 case SEC_OID_DES_EDE
:
316 case SEC_OID_DES_CBC
:
317 case SEC_OID_AES_128_CBC
:
318 case SEC_OID_AES_192_CBC
:
319 case SEC_OID_AES_256_CBC
:
320 case SEC_OID_FORTEZZA_SKIPJACK
:
321 case SEC_OID_DES_ECB
:
322 case SEC_OID_AES_128_ECB
:
323 case SEC_OID_AES_192_ECB
:
324 case SEC_OID_AES_256_ECB
:
325 case SEC_OID_DES_OFB
:
326 case SEC_OID_DES_CFB
:
327 /* Just encode the initVector as an octet string. */
328 if (!SEC_ASN1EncodeItem(poolp
, &algid
->parameters
,
329 &initVector
, kSecAsn1OctetStringTemplate
))
332 case SEC_OID_RC2_CBC
:
335 sec_rc2cbcParameter rc2
= {};
336 unsigned long rc2version
;
337 SecAsn1Item
*newParams
;
340 rc2version
= rc2_unmap(cssmKey
->KeyHeader
.LogicalKeySizeInBits
);
341 if (!SEC_ASN1EncodeUnsignedInteger (NULL
, &(rc2
.rc2ParameterVersion
),
344 newParams
= SEC_ASN1EncodeItem (poolp
, &algid
->parameters
, &rc2
,
345 sec_rc2cbc_parameter_template
);
346 PORT_Free(rc2
.rc2ParameterVersion
.Data
);
347 if (newParams
== NULL
)
352 case SEC_OID_RC5_CBC_PAD
:
354 // @@@ Implement rc5 params stuff.
360 // Extract IV from algid.parameters
361 // Put IV into algid.parameters
365 case SEC_OID_DES_EDE3_CBC
:
366 case SEC_OID_DES_EDE
:
367 case SEC_OID_DES_CBC
:
368 case SEC_OID_AES_128_CBC
:
369 case SEC_OID_AES_192_CBC
:
370 case SEC_OID_AES_256_CBC
:
371 case SEC_OID_FORTEZZA_SKIPJACK
:
372 case SEC_OID_DES_ECB
:
373 case SEC_OID_AES_128_ECB
:
374 case SEC_OID_AES_192_ECB
:
375 case SEC_OID_AES_256_ECB
:
376 case SEC_OID_DES_OFB
:
377 case SEC_OID_DES_CFB
:
380 /* Just decode the initVector from an octet string. */
381 rv
= SEC_ASN1DecodeItem(NULL
, &iv
, kSecAsn1OctetStringTemplate
, &(algid
->parameters
));
384 if (initVector
.Length
!= iv
.Length
) {
388 memcpy(initVector
.Data
, iv
.Data
, initVector
.Length
);
392 case SEC_OID_RC2_CBC
:
395 sec_rc2cbcParameter rc2
= {};
396 unsigned long ulEffectiveBits
;
398 rv
= SEC_ASN1DecodeItem(NULL
, &rc2
,sec_rc2cbc_parameter_template
,
399 &(algid
->parameters
));
403 if (initVector
.Length
!= rc2
.iv
.Length
) {
404 PORT_Free(rc2
.iv
.Data
);
405 PORT_Free(rc2
.rc2ParameterVersion
.Data
);
408 memcpy(initVector
.Data
, rc2
.iv
.Data
, initVector
.Length
);
409 PORT_Free(rc2
.iv
.Data
);
411 ulEffectiveBits
= rc2_map(&rc2
.rc2ParameterVersion
);
412 PORT_Free(rc2
.rc2ParameterVersion
.Data
);
413 if (ulEffectiveBits
!= cssmKey
->KeyHeader
.LogicalKeySizeInBits
)
418 case SEC_OID_RC5_CBC_PAD
:
420 // @@@ Implement rc5 params stuff.
426 if (CSSM_CSP_CreateSymmetricContext(cspHandle
,
429 NULL
, /* accessCred */
438 rv
= CSSM_EncryptDataInit(ciphercc
);
440 rv
= CSSM_DecryptDataInit(ciphercc
);
444 if (CCCryptorCreate(encrypt
? kCCEncrypt
: kCCDecrypt
,
445 alg
, cipheroptions
, CFDataGetBytePtr(key
), CFDataGetLength(key
),
446 initVector
.Data
, &ciphercc
))
450 cc
= (SecCmsCipherContextRef
)PORT_ZAlloc(sizeof(SecCmsCipherContext
));
455 cc
->encrypt
= encrypt
;
457 cc
->block_size
=cipher_blocksize
;
463 CSSM_DeleteContext(ciphercc
);
465 CCCryptorRelease(ciphercc
);
472 * SecCmsCipherContextStartDecrypt - create a cipher context to do decryption
473 * based on the given bulk * encryption key and algorithm identifier (which may include an iv).
475 * XXX Once both are working, it might be nice to combine this and the
476 * function below (for starting up encryption) into one routine, and just
477 * have two simple cover functions which call it.
479 SecCmsCipherContextRef
480 SecCmsCipherContextStartDecrypt(SecSymmetricKeyRef key
, SECAlgorithmID
*algid
)
482 return SecCmsCipherContextStart(NULL
, key
, algid
, PR_FALSE
);
484 SecCmsCipherContextRef cc
;
486 CK_MECHANISM_TYPE mechanism
;
491 algtag
= SECOID_GetAlgorithmTag(algid
);
493 /* set param and mechanism */
494 if (SEC_PKCS5IsAlgorithmPBEAlg(algid
)) {
495 CK_MECHANISM pbeMech
, cryptoMech
;
496 SecAsn1Item
* pbeParams
;
497 SEC_PKCS5KeyAndPassword
*keyPwd
;
499 PORT_Memset(&pbeMech
, 0, sizeof(CK_MECHANISM
));
500 PORT_Memset(&cryptoMech
, 0, sizeof(CK_MECHANISM
));
503 * in this case, key is not actually a SecSymmetricKeyRef, but a SEC_PKCS5KeyAndPassword *
505 keyPwd
= (SEC_PKCS5KeyAndPassword
*)key
;
508 /* find correct PK11 mechanism and parameters to initialize pbeMech */
509 pbeMech
.mechanism
= PK11_AlgtagToMechanism(algtag
);
510 pbeParams
= PK11_ParamFromAlgid(algid
);
513 pbeMech
.pParameter
= pbeParams
->Data
;
514 pbeMech
.ulParameterLen
= pbeParams
->Length
;
516 /* now map pbeMech to cryptoMech */
517 if (PK11_MapPBEMechanismToCryptoMechanism(&pbeMech
, &cryptoMech
, keyPwd
->pwitem
,
518 PR_FALSE
) != CKR_OK
) {
519 SECITEM_ZfreeItem(pbeParams
, PR_TRUE
);
522 SECITEM_ZfreeItem(pbeParams
, PR_TRUE
);
524 /* and use it to initialize param & mechanism */
525 if ((param
= (SecAsn1Item
*)PORT_ZAlloc(sizeof(SecAsn1Item
))) == NULL
)
528 param
->Data
= (unsigned char *)cryptoMech
.pParameter
;
529 param
->Length
= cryptoMech
.ulParameterLen
;
530 mechanism
= cryptoMech
.mechanism
;
532 mechanism
= PK11_AlgtagToMechanism(algtag
);
533 if ((param
= PK11_ParamFromAlgid(algid
)) == NULL
)
537 cc
= (SecCmsCipherContextRef
)PORT_ZAlloc(sizeof(SecCmsCipherContext
));
539 SECITEM_FreeItem(param
,PR_TRUE
);
543 /* figure out pad and block sizes */
544 cc
->pad_size
= PK11_GetBlockSize(mechanism
, param
);
545 slot
= PK11_GetSlotFromKey(key
);
546 cc
->block_size
= PK11_IsHW(slot
) ? BLOCK_SIZE
: cc
->pad_size
;
549 /* create PK11 cipher context */
550 ciphercx
= PK11_CreateContextBySymKey(mechanism
, CKA_DECRYPT
, key
, param
);
551 SECITEM_FreeItem(param
, PR_TRUE
);
552 if (ciphercx
== NULL
) {
558 cc
->doit
= (nss_cms_cipher_function
) PK11_CipherOp
;
559 cc
->destroy
= (nss_cms_cipher_destroy
) PK11_DestroyContext
;
560 cc
->encrypt
= PR_FALSE
;
561 cc
->pending_count
= 0;
568 * SecCmsCipherContextStartEncrypt - create a cipher object to do encryption,
569 * based on the given bulk encryption key and algorithm tag. Fill in the algorithm
570 * identifier (which may include an iv) appropriately.
572 * XXX Once both are working, it might be nice to combine this and the
573 * function above (for starting up decryption) into one routine, and just
574 * have two simple cover functions which call it.
576 SecCmsCipherContextRef
577 SecCmsCipherContextStartEncrypt(PRArenaPool
*poolp
, SecSymmetricKeyRef key
, SECAlgorithmID
*algid
)
579 return SecCmsCipherContextStart(poolp
, key
, algid
, PR_TRUE
);
581 SecCmsCipherContextRef cc
;
585 CK_MECHANISM_TYPE mechanism
;
587 Boolean needToEncodeAlgid
= PR_FALSE
;
588 SECOidTag algtag
= SECOID_GetAlgorithmTag(algid
);
590 /* set param and mechanism */
591 if (SEC_PKCS5IsAlgorithmPBEAlg(algid
)) {
592 CK_MECHANISM pbeMech
, cryptoMech
;
593 SecAsn1Item
* pbeParams
;
594 SEC_PKCS5KeyAndPassword
*keyPwd
;
596 PORT_Memset(&pbeMech
, 0, sizeof(CK_MECHANISM
));
597 PORT_Memset(&cryptoMech
, 0, sizeof(CK_MECHANISM
));
600 * in this case, key is not actually a SecSymmetricKeyRef, but a SEC_PKCS5KeyAndPassword *
602 keyPwd
= (SEC_PKCS5KeyAndPassword
*)key
;
605 /* find correct PK11 mechanism and parameters to initialize pbeMech */
606 pbeMech
.mechanism
= PK11_AlgtagToMechanism(algtag
);
607 pbeParams
= PK11_ParamFromAlgid(algid
);
610 pbeMech
.pParameter
= pbeParams
->Data
;
611 pbeMech
.ulParameterLen
= pbeParams
->Length
;
613 /* now map pbeMech to cryptoMech */
614 if (PK11_MapPBEMechanismToCryptoMechanism(&pbeMech
, &cryptoMech
, keyPwd
->pwitem
,
615 PR_FALSE
) != CKR_OK
) {
616 SECITEM_ZfreeItem(pbeParams
, PR_TRUE
);
619 SECITEM_ZfreeItem(pbeParams
, PR_TRUE
);
621 /* and use it to initialize param & mechanism */
622 if ((param
= (SecAsn1Item
*)PORT_ZAlloc(sizeof(SecAsn1Item
))) == NULL
)
625 param
->Data
= (unsigned char *)cryptoMech
.pParameter
;
626 param
->Length
= cryptoMech
.ulParameterLen
;
627 mechanism
= cryptoMech
.mechanism
;
629 mechanism
= PK11_AlgtagToMechanism(algtag
);
630 if ((param
= PK11_GenerateNewParam(mechanism
, key
)) == NULL
)
632 needToEncodeAlgid
= PR_TRUE
;
635 cc
= (SecCmsCipherContextRef
)PORT_ZAlloc(sizeof(SecCmsCipherContext
));
639 /* now find pad and block sizes for our mechanism */
640 cc
->pad_size
= PK11_GetBlockSize(mechanism
,param
);
641 slot
= PK11_GetSlotFromKey(key
);
642 cc
->block_size
= PK11_IsHW(slot
) ? BLOCK_SIZE
: cc
->pad_size
;
645 /* and here we go, creating a PK11 cipher context */
646 ciphercx
= PK11_CreateContextBySymKey(mechanism
, CKA_ENCRYPT
, key
, param
);
647 if (ciphercx
== NULL
) {
654 * These are placed after the CreateContextBySymKey() because some
655 * mechanisms have to generate their IVs from their card (i.e. FORTEZZA).
656 * Don't move it from here.
657 * XXX is that right? the purpose of this is to get the correct algid
658 * containing the IVs etc. for encoding. this means we need to set this up
659 * BEFORE encoding the algid in the contentInfo, right?
661 if (needToEncodeAlgid
) {
662 rv
= PK11_ParamToAlgid(algtag
, param
, poolp
, algid
);
663 if(rv
!= SECSuccess
) {
671 cc
->doit
= (nss_cms_cipher_function
)PK11_CipherOp
;
672 cc
->destroy
= (nss_cms_cipher_destroy
)PK11_DestroyContext
;
673 cc
->encrypt
= PR_TRUE
;
674 cc
->pending_count
= 0;
677 SECITEM_FreeItem(param
, PR_TRUE
);
684 SecCmsCipherContextDestroy(SecCmsCipherContextRef cc
)
686 PORT_Assert(cc
!= NULL
);
690 CSSM_DeleteContext(cc
->cc
);
692 CCCryptorRelease(cc
->cc
);
698 SecCmsCipherContextLength(SecCmsCipherContextRef cc
, unsigned int input_len
, Boolean final
, Boolean encrypt
)
701 CSSM_QUERY_SIZE_DATA dataBlockSize
[2] = { { input_len
, 0 }, { input_len
, 0 } };
702 /* Hack CDSA treats the last block as the final one. So unless we are being asked to report the final size we ask for 2 block and ignore the second (final) one. */
703 OSStatus rv
= CSSM_QuerySize(cc
->cc
, cc
->encrypt
, final
? 1 : 2, dataBlockSize
);
710 return dataBlockSize
[0].SizeOutputBlock
;
712 return ((input_len
+ cc
->block_size
- 1) / cc
->block_size
* cc
->block_size
) + (final
? cc
->block_size
: 0);
717 * SecCmsCipherContextDecryptLength - find the output length of the next call to decrypt.
719 * cc - the cipher context
720 * input_len - number of bytes used as input
721 * final - true if this is the final chunk of data
723 * Result can be used to perform memory allocations. Note that the amount
724 * is exactly accurate only when not doing a block cipher or when final
725 * is false, otherwise it is an upper bound on the amount because until
726 * we see the data we do not know how many padding bytes there are
727 * (always between 1 and bsize).
729 * Note that this can return zero, which does not mean that the decrypt
730 * operation can be skipped! (It simply means that there are not enough
731 * bytes to make up an entire block; the bytes will be reserved until
732 * there are enough to encrypt/decrypt at least one block.) However,
733 * if zero is returned it *does* mean that no output buffer need be
734 * passed in to the subsequent decrypt operation, as no output bytes
738 SecCmsCipherContextDecryptLength(SecCmsCipherContextRef cc
, unsigned int input_len
, Boolean final
)
741 return SecCmsCipherContextLength(cc
, input_len
, final
, PR_FALSE
);
743 int blocks
, block_size
;
745 PORT_Assert (! cc
->encrypt
);
747 block_size
= cc
->block_size
;
750 * If this is not a block cipher, then we always have the same
751 * number of output bytes as we had input bytes.
757 * On the final call, we will always use up all of the pending
758 * bytes plus all of the input bytes, *but*, there will be padding
759 * at the end and we cannot predict how many bytes of padding we
760 * will end up removing. The amount given here is actually known
761 * to be at least 1 byte too long (because we know we will have
762 * at least 1 byte of padding), but seemed clearer/better to me.
765 return cc
->pending_count
+ input_len
;
768 * Okay, this amount is exactly what we will output on the
769 * next cipher operation. We will always hang onto the last
770 * 1 - block_size bytes for non-final operations. That is,
771 * we will do as many complete blocks as we can *except* the
772 * last block (complete or partial). (This is because until
773 * we know we are at the end, we cannot know when to interpret
774 * and removing the padding byte(s), which are guaranteed to
777 blocks
= (cc
->pending_count
+ input_len
- 1) / block_size
;
778 return blocks
* block_size
;
783 * SecCmsCipherContextEncryptLength - find the output length of the next call to encrypt.
785 * cc - the cipher context
786 * input_len - number of bytes used as input
787 * final - true if this is the final chunk of data
789 * Result can be used to perform memory allocations.
791 * Note that this can return zero, which does not mean that the encrypt
792 * operation can be skipped! (It simply means that there are not enough
793 * bytes to make up an entire block; the bytes will be reserved until
794 * there are enough to encrypt/decrypt at least one block.) However,
795 * if zero is returned it *does* mean that no output buffer need be
796 * passed in to the subsequent encrypt operation, as no output bytes
800 SecCmsCipherContextEncryptLength(SecCmsCipherContextRef cc
, unsigned int input_len
, Boolean final
)
803 return SecCmsCipherContextLength(cc
, input_len
, final
, PR_TRUE
);
805 int blocks
, block_size
;
808 PORT_Assert (cc
->encrypt
);
810 block_size
= cc
->block_size
;
811 pad_size
= cc
->pad_size
;
814 * If this is not a block cipher, then we always have the same
815 * number of output bytes as we had input bytes.
821 * On the final call, we only send out what we need for
822 * remaining bytes plus the padding. (There is always padding,
823 * so even if we have an exact number of blocks as input, we
824 * will add another full block that is just padding.)
828 return cc
->pending_count
+ input_len
;
830 blocks
= (cc
->pending_count
+ input_len
) / pad_size
;
832 return blocks
*pad_size
;
837 * Now, count the number of complete blocks of data we have.
839 blocks
= (cc
->pending_count
+ input_len
) / block_size
;
842 return blocks
* block_size
;
848 SecCmsCipherContextCrypt(SecCmsCipherContextRef cc
, unsigned char *output
,
849 unsigned int *output_len_p
, unsigned int max_output_len
,
850 const unsigned char *input
, unsigned int input_len
,
851 Boolean final
, Boolean encrypt
)
853 size_t bytes_output
= 0;
860 SecAsn1Item inputBuf
= { input_len
, (uint8_t *)input
};
861 SecAsn1Item outputBuf
= { max_output_len
, output
};
863 rv
= CSSM_EncryptDataUpdate(cc
->cc
, &inputBuf
, 1, &outputBuf
, 1, &bytes_output
);
865 rv
= CSSM_DecryptDataUpdate(cc
->cc
, &inputBuf
, 1, &outputBuf
, 1, &bytes_output
);
867 rv
= CCCryptorUpdate(cc
->cc
, input
, input_len
, output
, max_output_len
, &bytes_output
);
874 SecAsn1Item remainderBuf
= { max_output_len
- bytes_output
, output
+ bytes_output
};
876 rv
= CSSM_EncryptDataFinal(cc
->cc
, &remainderBuf
);
878 rv
= CSSM_DecryptDataFinal(cc
->cc
, &remainderBuf
);
879 bytes_output
+= remainderBuf
.Length
;
881 size_t bytes_output_final
= 0;
882 rv
= CCCryptorFinal(cc
->cc
, output
+bytes_output
, max_output_len
-bytes_output
, &bytes_output_final
);
883 bytes_output
+= bytes_output_final
;
887 PORT_SetError(SEC_ERROR_BAD_DATA
);
888 else if (output_len_p
)
889 *output_len_p
= (unsigned int)bytes_output
; /* This cast is safe since bytes_output can't be bigger than max_output_len */
895 * SecCmsCipherContextDecrypt - do the decryption
897 * cc - the cipher context
898 * output - buffer for decrypted result bytes
899 * output_len_p - number of bytes in output
900 * max_output_len - upper bound on bytes to put into output
901 * input - pointer to input bytes
902 * input_len - number of input bytes
903 * final - true if this is the final chunk of data
905 * Decrypts a given length of input buffer (starting at "input" and
906 * containing "input_len" bytes), placing the decrypted bytes in
907 * "output" and storing the output length in "*output_len_p".
908 * "cc" is the return value from SecCmsCipherStartDecrypt.
909 * When "final" is true, this is the last of the data to be decrypted.
911 * This is much more complicated than it sounds when the cipher is
912 * a block-type, meaning that the decryption function will only
913 * operate on whole blocks. But our caller is operating stream-wise,
914 * and can pass in any number of bytes. So we need to keep track
915 * of block boundaries. We save excess bytes between calls in "cc".
916 * We also need to determine which bytes are padding, and remove
917 * them from the output. We can only do this step when we know we
918 * have the final block of data. PKCS #7 specifies that the padding
919 * used for a block cipher is a string of bytes, each of whose value is
920 * the same as the length of the padding, and that all data is padded.
921 * (Even data that starts out with an exact multiple of blocks gets
922 * added to it another block, all of which is padding.)
925 SecCmsCipherContextDecrypt(SecCmsCipherContextRef cc
, unsigned char *output
,
926 unsigned int *output_len_p
, unsigned int max_output_len
,
927 const unsigned char *input
, unsigned int input_len
,
931 return SecCmsCipherContextCrypt(cc
, output
,
932 output_len_p
, max_output_len
,
936 int blocks
, bsize
, pcount
, padsize
;
937 unsigned int max_needed
, ifraglen
, ofraglen
, output_len
;
941 PORT_Assert (! cc
->encrypt
);
944 * Check that we have enough room for the output. Our caller should
945 * already handle this; failure is really an internal error (i.e. bug).
947 max_needed
= SecCmsCipherContextDecryptLength(cc
, input_len
, final
);
948 PORT_Assert (max_output_len
>= max_needed
);
949 if (max_output_len
< max_needed
) {
950 /* PORT_SetError (XXX); */
955 * hardware encryption does not like small decryption sizes here, so we
956 * allow both blocking and padding.
958 bsize
= cc
->block_size
;
959 padsize
= cc
->pad_size
;
962 * When no blocking or padding work to do, we can simply call the
963 * cipher function and we are done.
966 return (* cc
->doit
) (cc
->cx
, output
, output_len_p
, max_output_len
,
970 pcount
= cc
->pending_count
;
971 pbuf
= cc
->pending_buf
;
977 * Try to fill in an entire block, starting with the bytes
978 * we already have saved away.
980 while (input_len
&& pcount
< bsize
) {
981 pbuf
[pcount
++] = *input
++;
985 * If we have at most a whole block and this is not our last call,
986 * then we are done for now. (We do not try to decrypt a lone
987 * single block because we cannot interpret the padding bytes
988 * until we know we are handling the very last block of all input.)
990 if (input_len
== 0 && !final
) {
991 cc
->pending_count
= pcount
;
997 * Given the logic above, we expect to have a full block by now.
998 * If we do not, there is something wrong, either with our own
999 * logic or with (length of) the data given to us.
1001 if ((padsize
!= 0) && (pcount
% padsize
) != 0) {
1002 PORT_Assert (final
);
1003 PORT_SetError (SEC_ERROR_BAD_DATA
);
1007 * Decrypt the block.
1009 rv
= (*cc
->doit
)(cc
->cx
, output
, &ofraglen
, max_output_len
,
1011 if (rv
!= SECSuccess
)
1015 * For now anyway, all of our ciphers have the same number of
1016 * bytes of output as they do input. If this ever becomes untrue,
1017 * then SecCmsCipherContextDecryptLength needs to be made smarter!
1019 PORT_Assert(ofraglen
== pcount
);
1022 * Account for the bytes now in output.
1024 max_output_len
-= ofraglen
;
1025 output_len
+= ofraglen
;
1030 * If this is our last call, we expect to have an exact number of
1031 * blocks left to be decrypted; we will decrypt them all.
1033 * If not our last call, we always save between 1 and bsize bytes
1034 * until next time. (We must do this because we cannot be sure
1035 * that none of the decrypted bytes are padding bytes until we
1036 * have at least another whole block of data. You cannot tell by
1037 * looking -- the data could be anything -- you can only tell by
1038 * context, knowing you are looking at the last block.) We could
1039 * decrypt a whole block now but it is easier if we just treat it
1040 * the same way we treat partial block bytes.
1044 blocks
= input_len
/ padsize
;
1045 ifraglen
= blocks
* padsize
;
1046 } else ifraglen
= input_len
;
1047 PORT_Assert (ifraglen
== input_len
);
1049 if (ifraglen
!= input_len
) {
1050 PORT_SetError(SEC_ERROR_BAD_DATA
);
1054 blocks
= (input_len
- 1) / bsize
;
1055 ifraglen
= blocks
* bsize
;
1056 PORT_Assert (ifraglen
< input_len
);
1058 pcount
= input_len
- ifraglen
;
1059 PORT_Memcpy (pbuf
, input
+ ifraglen
, pcount
);
1060 cc
->pending_count
= pcount
;
1064 rv
= (* cc
->doit
)(cc
->cx
, output
, &ofraglen
, max_output_len
,
1066 if (rv
!= SECSuccess
)
1070 * For now anyway, all of our ciphers have the same number of
1071 * bytes of output as they do input. If this ever becomes untrue,
1072 * then sec_PKCS7DecryptLength needs to be made smarter!
1074 PORT_Assert (ifraglen
== ofraglen
);
1075 if (ifraglen
!= ofraglen
) {
1076 PORT_SetError(SEC_ERROR_BAD_DATA
);
1080 output_len
+= ofraglen
;
1086 * If we just did our very last block, "remove" the padding by
1087 * adjusting the output length.
1089 if (final
&& (padsize
!= 0)) {
1090 unsigned int padlen
= *(output
+ ofraglen
- 1);
1092 if (padlen
== 0 || padlen
> padsize
) {
1093 PORT_SetError(SEC_ERROR_BAD_DATA
);
1096 output_len
-= padlen
;
1099 PORT_Assert (output_len_p
!= NULL
|| output_len
== 0);
1100 if (output_len_p
!= NULL
)
1101 *output_len_p
= output_len
;
1108 * SecCmsCipherContextEncrypt - do the encryption
1110 * cc - the cipher context
1111 * output - buffer for decrypted result bytes
1112 * output_len_p - number of bytes in output
1113 * max_output_len - upper bound on bytes to put into output
1114 * input - pointer to input bytes
1115 * input_len - number of input bytes
1116 * final - true if this is the final chunk of data
1118 * Encrypts a given length of input buffer (starting at "input" and
1119 * containing "input_len" bytes), placing the encrypted bytes in
1120 * "output" and storing the output length in "*output_len_p".
1121 * "cc" is the return value from SecCmsCipherStartEncrypt.
1122 * When "final" is true, this is the last of the data to be encrypted.
1124 * This is much more complicated than it sounds when the cipher is
1125 * a block-type, meaning that the encryption function will only
1126 * operate on whole blocks. But our caller is operating stream-wise,
1127 * and can pass in any number of bytes. So we need to keep track
1128 * of block boundaries. We save excess bytes between calls in "cc".
1129 * We also need to add padding bytes at the end. PKCS #7 specifies
1130 * that the padding used for a block cipher is a string of bytes,
1131 * each of whose value is the same as the length of the padding,
1132 * and that all data is padded. (Even data that starts out with
1133 * an exact multiple of blocks gets added to it another block,
1134 * all of which is padding.)
1136 * XXX I would kind of like to combine this with the function above
1137 * which does decryption, since they have a lot in common. But the
1138 * tricky parts about padding and filling blocks would be much
1139 * harder to read that way, so I left them separate. At least for
1140 * now until it is clear that they are right.
1143 SecCmsCipherContextEncrypt(SecCmsCipherContextRef cc
, unsigned char *output
,
1144 unsigned int *output_len_p
, unsigned int max_output_len
,
1145 const unsigned char *input
, unsigned int input_len
,
1149 return SecCmsCipherContextCrypt(cc
, output
,
1150 output_len_p
, max_output_len
,
1154 int blocks
, bsize
, padlen
, pcount
, padsize
;
1155 unsigned int max_needed
, ifraglen
, ofraglen
, output_len
;
1156 unsigned char *pbuf
;
1159 PORT_Assert (cc
->encrypt
);
1162 * Check that we have enough room for the output. Our caller should
1163 * already handle this; failure is really an internal error (i.e. bug).
1165 max_needed
= SecCmsCipherContextEncryptLength (cc
, input_len
, final
);
1166 PORT_Assert (max_output_len
>= max_needed
);
1167 if (max_output_len
< max_needed
) {
1168 /* PORT_SetError (XXX); */
1172 bsize
= cc
->block_size
;
1173 padsize
= cc
->pad_size
;
1176 * When no blocking and padding work to do, we can simply call the
1177 * cipher function and we are done.
1180 return (*cc
->doit
)(cc
->cx
, output
, output_len_p
, max_output_len
,
1184 pcount
= cc
->pending_count
;
1185 pbuf
= cc
->pending_buf
;
1191 * Try to fill in an entire block, starting with the bytes
1192 * we already have saved away.
1194 while (input_len
&& pcount
< bsize
) {
1195 pbuf
[pcount
++] = *input
++;
1199 * If we do not have a full block and we know we will be
1200 * called again, then we are done for now.
1202 if (pcount
< bsize
&& !final
) {
1203 cc
->pending_count
= pcount
;
1204 if (output_len_p
!= NULL
)
1209 * If we have a whole block available, encrypt it.
1211 if ((padsize
== 0) || (pcount
% padsize
) == 0) {
1212 rv
= (* cc
->doit
) (cc
->cx
, output
, &ofraglen
, max_output_len
,
1214 if (rv
!= SECSuccess
)
1218 * For now anyway, all of our ciphers have the same number of
1219 * bytes of output as they do input. If this ever becomes untrue,
1220 * then sec_PKCS7EncryptLength needs to be made smarter!
1222 PORT_Assert (ofraglen
== pcount
);
1225 * Account for the bytes now in output.
1227 max_output_len
-= ofraglen
;
1228 output_len
+= ofraglen
;
1236 PORT_Assert (pcount
== 0);
1238 blocks
= input_len
/ bsize
;
1239 ifraglen
= blocks
* bsize
;
1242 rv
= (* cc
->doit
) (cc
->cx
, output
, &ofraglen
, max_output_len
,
1244 if (rv
!= SECSuccess
)
1248 * For now anyway, all of our ciphers have the same number of
1249 * bytes of output as they do input. If this ever becomes untrue,
1250 * then sec_PKCS7EncryptLength needs to be made smarter!
1252 PORT_Assert (ifraglen
== ofraglen
);
1254 max_output_len
-= ofraglen
;
1255 output_len
+= ofraglen
;
1259 pcount
= input_len
- ifraglen
;
1260 PORT_Assert (pcount
< bsize
);
1262 PORT_Memcpy (pbuf
, input
+ ifraglen
, pcount
);
1266 padlen
= padsize
- (pcount
% padsize
);
1267 PORT_Memset (pbuf
+ pcount
, padlen
, padlen
);
1268 rv
= (* cc
->doit
) (cc
->cx
, output
, &ofraglen
, max_output_len
,
1269 pbuf
, pcount
+padlen
);
1270 if (rv
!= SECSuccess
)
1274 * For now anyway, all of our ciphers have the same number of
1275 * bytes of output as they do input. If this ever becomes untrue,
1276 * then sec_PKCS7EncryptLength needs to be made smarter!
1278 PORT_Assert (ofraglen
== (pcount
+padlen
));
1279 output_len
+= ofraglen
;
1281 cc
->pending_count
= pcount
;
1284 PORT_Assert (output_len_p
!= NULL
|| output_len
== 0);
1285 if (output_len_p
!= NULL
)
1286 *output_len_p
= output_len
;