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.
361 // Extract IV from algid.parameters
362 // Put IV into algid.parameters
366 case SEC_OID_DES_EDE3_CBC
:
367 case SEC_OID_DES_EDE
:
368 case SEC_OID_DES_CBC
:
369 case SEC_OID_AES_128_CBC
:
370 case SEC_OID_AES_192_CBC
:
371 case SEC_OID_AES_256_CBC
:
372 case SEC_OID_FORTEZZA_SKIPJACK
:
373 case SEC_OID_DES_ECB
:
374 case SEC_OID_AES_128_ECB
:
375 case SEC_OID_AES_192_ECB
:
376 case SEC_OID_AES_256_ECB
:
377 case SEC_OID_DES_OFB
:
378 case SEC_OID_DES_CFB
:
381 /* Just decode the initVector from an octet string. */
382 rv
= SEC_ASN1DecodeItem(NULL
, &iv
, kSecAsn1OctetStringTemplate
, &(algid
->parameters
));
385 if (initVector
.Length
!= iv
.Length
) {
389 memcpy(initVector
.Data
, iv
.Data
, initVector
.Length
);
393 case SEC_OID_RC2_CBC
:
396 sec_rc2cbcParameter rc2
= {};
397 unsigned long ulEffectiveBits
;
399 rv
= SEC_ASN1DecodeItem(NULL
, &rc2
,sec_rc2cbc_parameter_template
,
400 &(algid
->parameters
));
404 if (initVector
.Length
!= rc2
.iv
.Length
) {
405 PORT_Free(rc2
.iv
.Data
);
406 PORT_Free(rc2
.rc2ParameterVersion
.Data
);
409 memcpy(initVector
.Data
, rc2
.iv
.Data
, initVector
.Length
);
410 PORT_Free(rc2
.iv
.Data
);
412 ulEffectiveBits
= rc2_map(&rc2
.rc2ParameterVersion
);
413 PORT_Free(rc2
.rc2ParameterVersion
.Data
);
414 if (ulEffectiveBits
!= cssmKey
->KeyHeader
.LogicalKeySizeInBits
)
419 case SEC_OID_RC5_CBC_PAD
:
421 // @@@ Implement rc5 params stuff.
428 if (CSSM_CSP_CreateSymmetricContext(cspHandle
,
431 NULL
, /* accessCred */
440 rv
= CSSM_EncryptDataInit(ciphercc
);
442 rv
= CSSM_DecryptDataInit(ciphercc
);
446 if (CCCryptorCreate(encrypt
? kCCEncrypt
: kCCDecrypt
,
447 alg
, cipheroptions
, CFDataGetBytePtr(key
), CFDataGetLength(key
),
448 initVector
.Data
, &ciphercc
))
452 cc
= (SecCmsCipherContextRef
)PORT_ZAlloc(sizeof(SecCmsCipherContext
));
457 cc
->encrypt
= encrypt
;
459 cc
->block_size
=cipher_blocksize
;
465 CSSM_DeleteContext(ciphercc
);
467 CCCryptorRelease(ciphercc
);
474 * SecCmsCipherContextStartDecrypt - create a cipher context to do decryption
475 * based on the given bulk * encryption key and algorithm identifier (which may include an iv).
477 * XXX Once both are working, it might be nice to combine this and the
478 * function below (for starting up encryption) into one routine, and just
479 * have two simple cover functions which call it.
481 SecCmsCipherContextRef
482 SecCmsCipherContextStartDecrypt(SecSymmetricKeyRef key
, SECAlgorithmID
*algid
)
484 return SecCmsCipherContextStart(NULL
, key
, algid
, PR_FALSE
);
486 SecCmsCipherContextRef cc
;
488 CK_MECHANISM_TYPE mechanism
;
493 algtag
= SECOID_GetAlgorithmTag(algid
);
495 /* set param and mechanism */
496 if (SEC_PKCS5IsAlgorithmPBEAlg(algid
)) {
497 CK_MECHANISM pbeMech
, cryptoMech
;
498 SecAsn1Item
* pbeParams
;
499 SEC_PKCS5KeyAndPassword
*keyPwd
;
501 PORT_Memset(&pbeMech
, 0, sizeof(CK_MECHANISM
));
502 PORT_Memset(&cryptoMech
, 0, sizeof(CK_MECHANISM
));
505 * in this case, key is not actually a SecSymmetricKeyRef, but a SEC_PKCS5KeyAndPassword *
507 keyPwd
= (SEC_PKCS5KeyAndPassword
*)key
;
510 /* find correct PK11 mechanism and parameters to initialize pbeMech */
511 pbeMech
.mechanism
= PK11_AlgtagToMechanism(algtag
);
512 pbeParams
= PK11_ParamFromAlgid(algid
);
515 pbeMech
.pParameter
= pbeParams
->Data
;
516 pbeMech
.ulParameterLen
= pbeParams
->Length
;
518 /* now map pbeMech to cryptoMech */
519 if (PK11_MapPBEMechanismToCryptoMechanism(&pbeMech
, &cryptoMech
, keyPwd
->pwitem
,
520 PR_FALSE
) != CKR_OK
) {
521 SECITEM_ZfreeItem(pbeParams
, PR_TRUE
);
524 SECITEM_ZfreeItem(pbeParams
, PR_TRUE
);
526 /* and use it to initialize param & mechanism */
527 if ((param
= (SecAsn1Item
*)PORT_ZAlloc(sizeof(SecAsn1Item
))) == NULL
)
530 param
->Data
= (unsigned char *)cryptoMech
.pParameter
;
531 param
->Length
= cryptoMech
.ulParameterLen
;
532 mechanism
= cryptoMech
.mechanism
;
534 mechanism
= PK11_AlgtagToMechanism(algtag
);
535 if ((param
= PK11_ParamFromAlgid(algid
)) == NULL
)
539 cc
= (SecCmsCipherContextRef
)PORT_ZAlloc(sizeof(SecCmsCipherContext
));
541 SECITEM_FreeItem(param
,PR_TRUE
);
545 /* figure out pad and block sizes */
546 cc
->pad_size
= PK11_GetBlockSize(mechanism
, param
);
547 slot
= PK11_GetSlotFromKey(key
);
548 cc
->block_size
= PK11_IsHW(slot
) ? BLOCK_SIZE
: cc
->pad_size
;
551 /* create PK11 cipher context */
552 ciphercx
= PK11_CreateContextBySymKey(mechanism
, CKA_DECRYPT
, key
, param
);
553 SECITEM_FreeItem(param
, PR_TRUE
);
554 if (ciphercx
== NULL
) {
560 cc
->doit
= (nss_cms_cipher_function
) PK11_CipherOp
;
561 cc
->destroy
= (nss_cms_cipher_destroy
) PK11_DestroyContext
;
562 cc
->encrypt
= PR_FALSE
;
563 cc
->pending_count
= 0;
570 * SecCmsCipherContextStartEncrypt - create a cipher object to do encryption,
571 * based on the given bulk encryption key and algorithm tag. Fill in the algorithm
572 * identifier (which may include an iv) appropriately.
574 * XXX Once both are working, it might be nice to combine this and the
575 * function above (for starting up decryption) into one routine, and just
576 * have two simple cover functions which call it.
578 SecCmsCipherContextRef
579 SecCmsCipherContextStartEncrypt(PRArenaPool
*poolp
, SecSymmetricKeyRef key
, SECAlgorithmID
*algid
)
581 return SecCmsCipherContextStart(poolp
, key
, algid
, PR_TRUE
);
583 SecCmsCipherContextRef cc
;
587 CK_MECHANISM_TYPE mechanism
;
589 Boolean needToEncodeAlgid
= PR_FALSE
;
590 SECOidTag algtag
= SECOID_GetAlgorithmTag(algid
);
592 /* set param and mechanism */
593 if (SEC_PKCS5IsAlgorithmPBEAlg(algid
)) {
594 CK_MECHANISM pbeMech
, cryptoMech
;
595 SecAsn1Item
* pbeParams
;
596 SEC_PKCS5KeyAndPassword
*keyPwd
;
598 PORT_Memset(&pbeMech
, 0, sizeof(CK_MECHANISM
));
599 PORT_Memset(&cryptoMech
, 0, sizeof(CK_MECHANISM
));
602 * in this case, key is not actually a SecSymmetricKeyRef, but a SEC_PKCS5KeyAndPassword *
604 keyPwd
= (SEC_PKCS5KeyAndPassword
*)key
;
607 /* find correct PK11 mechanism and parameters to initialize pbeMech */
608 pbeMech
.mechanism
= PK11_AlgtagToMechanism(algtag
);
609 pbeParams
= PK11_ParamFromAlgid(algid
);
612 pbeMech
.pParameter
= pbeParams
->Data
;
613 pbeMech
.ulParameterLen
= pbeParams
->Length
;
615 /* now map pbeMech to cryptoMech */
616 if (PK11_MapPBEMechanismToCryptoMechanism(&pbeMech
, &cryptoMech
, keyPwd
->pwitem
,
617 PR_FALSE
) != CKR_OK
) {
618 SECITEM_ZfreeItem(pbeParams
, PR_TRUE
);
621 SECITEM_ZfreeItem(pbeParams
, PR_TRUE
);
623 /* and use it to initialize param & mechanism */
624 if ((param
= (SecAsn1Item
*)PORT_ZAlloc(sizeof(SecAsn1Item
))) == NULL
)
627 param
->Data
= (unsigned char *)cryptoMech
.pParameter
;
628 param
->Length
= cryptoMech
.ulParameterLen
;
629 mechanism
= cryptoMech
.mechanism
;
631 mechanism
= PK11_AlgtagToMechanism(algtag
);
632 if ((param
= PK11_GenerateNewParam(mechanism
, key
)) == NULL
)
634 needToEncodeAlgid
= PR_TRUE
;
637 cc
= (SecCmsCipherContextRef
)PORT_ZAlloc(sizeof(SecCmsCipherContext
));
641 /* now find pad and block sizes for our mechanism */
642 cc
->pad_size
= PK11_GetBlockSize(mechanism
,param
);
643 slot
= PK11_GetSlotFromKey(key
);
644 cc
->block_size
= PK11_IsHW(slot
) ? BLOCK_SIZE
: cc
->pad_size
;
647 /* and here we go, creating a PK11 cipher context */
648 ciphercx
= PK11_CreateContextBySymKey(mechanism
, CKA_ENCRYPT
, key
, param
);
649 if (ciphercx
== NULL
) {
656 * These are placed after the CreateContextBySymKey() because some
657 * mechanisms have to generate their IVs from their card (i.e. FORTEZZA).
658 * Don't move it from here.
659 * XXX is that right? the purpose of this is to get the correct algid
660 * containing the IVs etc. for encoding. this means we need to set this up
661 * BEFORE encoding the algid in the contentInfo, right?
663 if (needToEncodeAlgid
) {
664 rv
= PK11_ParamToAlgid(algtag
, param
, poolp
, algid
);
665 if(rv
!= SECSuccess
) {
673 cc
->doit
= (nss_cms_cipher_function
)PK11_CipherOp
;
674 cc
->destroy
= (nss_cms_cipher_destroy
)PK11_DestroyContext
;
675 cc
->encrypt
= PR_TRUE
;
676 cc
->pending_count
= 0;
679 SECITEM_FreeItem(param
, PR_TRUE
);
686 SecCmsCipherContextDestroy(SecCmsCipherContextRef cc
)
688 PORT_Assert(cc
!= NULL
);
692 CSSM_DeleteContext(cc
->cc
);
694 CCCryptorRelease(cc
->cc
);
700 SecCmsCipherContextLength(SecCmsCipherContextRef cc
, unsigned int input_len
, Boolean final
, Boolean encrypt
)
703 CSSM_QUERY_SIZE_DATA dataBlockSize
[2] = { { input_len
, 0 }, { input_len
, 0 } };
704 /* 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. */
705 OSStatus rv
= CSSM_QuerySize(cc
->cc
, cc
->encrypt
, final
? 1 : 2, dataBlockSize
);
712 return dataBlockSize
[0].SizeOutputBlock
;
714 return ((input_len
+ cc
->block_size
- 1) / cc
->block_size
* cc
->block_size
) + (final
? cc
->block_size
: 0);
719 * SecCmsCipherContextDecryptLength - find the output length of the next call to decrypt.
721 * cc - the cipher context
722 * input_len - number of bytes used as input
723 * final - true if this is the final chunk of data
725 * Result can be used to perform memory allocations. Note that the amount
726 * is exactly accurate only when not doing a block cipher or when final
727 * is false, otherwise it is an upper bound on the amount because until
728 * we see the data we do not know how many padding bytes there are
729 * (always between 1 and bsize).
731 * Note that this can return zero, which does not mean that the decrypt
732 * operation can be skipped! (It simply means that there are not enough
733 * bytes to make up an entire block; the bytes will be reserved until
734 * there are enough to encrypt/decrypt at least one block.) However,
735 * if zero is returned it *does* mean that no output buffer need be
736 * passed in to the subsequent decrypt operation, as no output bytes
740 SecCmsCipherContextDecryptLength(SecCmsCipherContextRef cc
, unsigned int input_len
, Boolean final
)
743 return SecCmsCipherContextLength(cc
, input_len
, final
, PR_FALSE
);
745 int blocks
, block_size
;
747 PORT_Assert (! cc
->encrypt
);
749 block_size
= cc
->block_size
;
752 * If this is not a block cipher, then we always have the same
753 * number of output bytes as we had input bytes.
759 * On the final call, we will always use up all of the pending
760 * bytes plus all of the input bytes, *but*, there will be padding
761 * at the end and we cannot predict how many bytes of padding we
762 * will end up removing. The amount given here is actually known
763 * to be at least 1 byte too long (because we know we will have
764 * at least 1 byte of padding), but seemed clearer/better to me.
767 return cc
->pending_count
+ input_len
;
770 * Okay, this amount is exactly what we will output on the
771 * next cipher operation. We will always hang onto the last
772 * 1 - block_size bytes for non-final operations. That is,
773 * we will do as many complete blocks as we can *except* the
774 * last block (complete or partial). (This is because until
775 * we know we are at the end, we cannot know when to interpret
776 * and removing the padding byte(s), which are guaranteed to
779 blocks
= (cc
->pending_count
+ input_len
- 1) / block_size
;
780 return blocks
* block_size
;
785 * SecCmsCipherContextEncryptLength - find the output length of the next call to encrypt.
787 * cc - the cipher context
788 * input_len - number of bytes used as input
789 * final - true if this is the final chunk of data
791 * Result can be used to perform memory allocations.
793 * Note that this can return zero, which does not mean that the encrypt
794 * operation can be skipped! (It simply means that there are not enough
795 * bytes to make up an entire block; the bytes will be reserved until
796 * there are enough to encrypt/decrypt at least one block.) However,
797 * if zero is returned it *does* mean that no output buffer need be
798 * passed in to the subsequent encrypt operation, as no output bytes
802 SecCmsCipherContextEncryptLength(SecCmsCipherContextRef cc
, unsigned int input_len
, Boolean final
)
805 return SecCmsCipherContextLength(cc
, input_len
, final
, PR_TRUE
);
807 int blocks
, block_size
;
810 PORT_Assert (cc
->encrypt
);
812 block_size
= cc
->block_size
;
813 pad_size
= cc
->pad_size
;
816 * If this is not a block cipher, then we always have the same
817 * number of output bytes as we had input bytes.
823 * On the final call, we only send out what we need for
824 * remaining bytes plus the padding. (There is always padding,
825 * so even if we have an exact number of blocks as input, we
826 * will add another full block that is just padding.)
830 return cc
->pending_count
+ input_len
;
832 blocks
= (cc
->pending_count
+ input_len
) / pad_size
;
834 return blocks
*pad_size
;
839 * Now, count the number of complete blocks of data we have.
841 blocks
= (cc
->pending_count
+ input_len
) / block_size
;
844 return blocks
* block_size
;
850 SecCmsCipherContextCrypt(SecCmsCipherContextRef cc
, unsigned char *output
,
851 unsigned int *output_len_p
, unsigned int max_output_len
,
852 const unsigned char *input
, unsigned int input_len
,
853 Boolean final
, Boolean encrypt
)
855 size_t bytes_output
= 0;
862 SecAsn1Item inputBuf
= { input_len
, (uint8_t *)input
};
863 SecAsn1Item outputBuf
= { max_output_len
, output
};
865 rv
= CSSM_EncryptDataUpdate(cc
->cc
, &inputBuf
, 1, &outputBuf
, 1, &bytes_output
);
867 rv
= CSSM_DecryptDataUpdate(cc
->cc
, &inputBuf
, 1, &outputBuf
, 1, &bytes_output
);
869 rv
= CCCryptorUpdate(cc
->cc
, input
, input_len
, output
, max_output_len
, &bytes_output
);
876 SecAsn1Item remainderBuf
= { max_output_len
- bytes_output
, output
+ bytes_output
};
878 rv
= CSSM_EncryptDataFinal(cc
->cc
, &remainderBuf
);
880 rv
= CSSM_DecryptDataFinal(cc
->cc
, &remainderBuf
);
881 bytes_output
+= remainderBuf
.Length
;
883 size_t bytes_output_final
= 0;
884 rv
= CCCryptorFinal(cc
->cc
, output
+bytes_output
, max_output_len
-bytes_output
, &bytes_output_final
);
885 bytes_output
+= bytes_output_final
;
889 PORT_SetError(SEC_ERROR_BAD_DATA
);
890 else if (output_len_p
)
891 *output_len_p
= (unsigned int)bytes_output
; /* This cast is safe since bytes_output can't be bigger than max_output_len */
897 * SecCmsCipherContextDecrypt - do the decryption
899 * cc - the cipher context
900 * output - buffer for decrypted result bytes
901 * output_len_p - number of bytes in output
902 * max_output_len - upper bound on bytes to put into output
903 * input - pointer to input bytes
904 * input_len - number of input bytes
905 * final - true if this is the final chunk of data
907 * Decrypts a given length of input buffer (starting at "input" and
908 * containing "input_len" bytes), placing the decrypted bytes in
909 * "output" and storing the output length in "*output_len_p".
910 * "cc" is the return value from SecCmsCipherStartDecrypt.
911 * When "final" is true, this is the last of the data to be decrypted.
913 * This is much more complicated than it sounds when the cipher is
914 * a block-type, meaning that the decryption function will only
915 * operate on whole blocks. But our caller is operating stream-wise,
916 * and can pass in any number of bytes. So we need to keep track
917 * of block boundaries. We save excess bytes between calls in "cc".
918 * We also need to determine which bytes are padding, and remove
919 * them from the output. We can only do this step when we know we
920 * have the final block of data. PKCS #7 specifies that the padding
921 * used for a block cipher is a string of bytes, each of whose value is
922 * the same as the length of the padding, and that all data is padded.
923 * (Even data that starts out with an exact multiple of blocks gets
924 * added to it another block, all of which is padding.)
927 SecCmsCipherContextDecrypt(SecCmsCipherContextRef cc
, unsigned char *output
,
928 unsigned int *output_len_p
, unsigned int max_output_len
,
929 const unsigned char *input
, unsigned int input_len
,
933 return SecCmsCipherContextCrypt(cc
, output
,
934 output_len_p
, max_output_len
,
938 int blocks
, bsize
, pcount
, padsize
;
939 unsigned int max_needed
, ifraglen
, ofraglen
, output_len
;
943 PORT_Assert (! cc
->encrypt
);
946 * Check that we have enough room for the output. Our caller should
947 * already handle this; failure is really an internal error (i.e. bug).
949 max_needed
= SecCmsCipherContextDecryptLength(cc
, input_len
, final
);
950 PORT_Assert (max_output_len
>= max_needed
);
951 if (max_output_len
< max_needed
) {
952 /* PORT_SetError (XXX); */
957 * hardware encryption does not like small decryption sizes here, so we
958 * allow both blocking and padding.
960 bsize
= cc
->block_size
;
961 padsize
= cc
->pad_size
;
964 * When no blocking or padding work to do, we can simply call the
965 * cipher function and we are done.
968 return (* cc
->doit
) (cc
->cx
, output
, output_len_p
, max_output_len
,
972 pcount
= cc
->pending_count
;
973 pbuf
= cc
->pending_buf
;
979 * Try to fill in an entire block, starting with the bytes
980 * we already have saved away.
982 while (input_len
&& pcount
< bsize
) {
983 pbuf
[pcount
++] = *input
++;
987 * If we have at most a whole block and this is not our last call,
988 * then we are done for now. (We do not try to decrypt a lone
989 * single block because we cannot interpret the padding bytes
990 * until we know we are handling the very last block of all input.)
992 if (input_len
== 0 && !final
) {
993 cc
->pending_count
= pcount
;
999 * Given the logic above, we expect to have a full block by now.
1000 * If we do not, there is something wrong, either with our own
1001 * logic or with (length of) the data given to us.
1003 if ((padsize
!= 0) && (pcount
% padsize
) != 0) {
1004 PORT_Assert (final
);
1005 PORT_SetError (SEC_ERROR_BAD_DATA
);
1009 * Decrypt the block.
1011 rv
= (*cc
->doit
)(cc
->cx
, output
, &ofraglen
, max_output_len
,
1013 if (rv
!= SECSuccess
)
1017 * For now anyway, all of our ciphers have the same number of
1018 * bytes of output as they do input. If this ever becomes untrue,
1019 * then SecCmsCipherContextDecryptLength needs to be made smarter!
1021 PORT_Assert(ofraglen
== pcount
);
1024 * Account for the bytes now in output.
1026 max_output_len
-= ofraglen
;
1027 output_len
+= ofraglen
;
1032 * If this is our last call, we expect to have an exact number of
1033 * blocks left to be decrypted; we will decrypt them all.
1035 * If not our last call, we always save between 1 and bsize bytes
1036 * until next time. (We must do this because we cannot be sure
1037 * that none of the decrypted bytes are padding bytes until we
1038 * have at least another whole block of data. You cannot tell by
1039 * looking -- the data could be anything -- you can only tell by
1040 * context, knowing you are looking at the last block.) We could
1041 * decrypt a whole block now but it is easier if we just treat it
1042 * the same way we treat partial block bytes.
1046 blocks
= input_len
/ padsize
;
1047 ifraglen
= blocks
* padsize
;
1048 } else ifraglen
= input_len
;
1049 PORT_Assert (ifraglen
== input_len
);
1051 if (ifraglen
!= input_len
) {
1052 PORT_SetError(SEC_ERROR_BAD_DATA
);
1056 blocks
= (input_len
- 1) / bsize
;
1057 ifraglen
= blocks
* bsize
;
1058 PORT_Assert (ifraglen
< input_len
);
1060 pcount
= input_len
- ifraglen
;
1061 PORT_Memcpy (pbuf
, input
+ ifraglen
, pcount
);
1062 cc
->pending_count
= pcount
;
1066 rv
= (* cc
->doit
)(cc
->cx
, output
, &ofraglen
, max_output_len
,
1068 if (rv
!= SECSuccess
)
1072 * For now anyway, all of our ciphers have the same number of
1073 * bytes of output as they do input. If this ever becomes untrue,
1074 * then sec_PKCS7DecryptLength needs to be made smarter!
1076 PORT_Assert (ifraglen
== ofraglen
);
1077 if (ifraglen
!= ofraglen
) {
1078 PORT_SetError(SEC_ERROR_BAD_DATA
);
1082 output_len
+= ofraglen
;
1088 * If we just did our very last block, "remove" the padding by
1089 * adjusting the output length.
1091 if (final
&& (padsize
!= 0)) {
1092 unsigned int padlen
= *(output
+ ofraglen
- 1);
1094 if (padlen
== 0 || padlen
> padsize
) {
1095 PORT_SetError(SEC_ERROR_BAD_DATA
);
1098 output_len
-= padlen
;
1101 PORT_Assert (output_len_p
!= NULL
|| output_len
== 0);
1102 if (output_len_p
!= NULL
)
1103 *output_len_p
= output_len
;
1110 * SecCmsCipherContextEncrypt - do the encryption
1112 * cc - the cipher context
1113 * output - buffer for decrypted result bytes
1114 * output_len_p - number of bytes in output
1115 * max_output_len - upper bound on bytes to put into output
1116 * input - pointer to input bytes
1117 * input_len - number of input bytes
1118 * final - true if this is the final chunk of data
1120 * Encrypts a given length of input buffer (starting at "input" and
1121 * containing "input_len" bytes), placing the encrypted bytes in
1122 * "output" and storing the output length in "*output_len_p".
1123 * "cc" is the return value from SecCmsCipherStartEncrypt.
1124 * When "final" is true, this is the last of the data to be encrypted.
1126 * This is much more complicated than it sounds when the cipher is
1127 * a block-type, meaning that the encryption function will only
1128 * operate on whole blocks. But our caller is operating stream-wise,
1129 * and can pass in any number of bytes. So we need to keep track
1130 * of block boundaries. We save excess bytes between calls in "cc".
1131 * We also need to add padding bytes at the end. PKCS #7 specifies
1132 * that the padding used for a block cipher is a string of bytes,
1133 * each of whose value is the same as the length of the padding,
1134 * and that all data is padded. (Even data that starts out with
1135 * an exact multiple of blocks gets added to it another block,
1136 * all of which is padding.)
1138 * XXX I would kind of like to combine this with the function above
1139 * which does decryption, since they have a lot in common. But the
1140 * tricky parts about padding and filling blocks would be much
1141 * harder to read that way, so I left them separate. At least for
1142 * now until it is clear that they are right.
1145 SecCmsCipherContextEncrypt(SecCmsCipherContextRef cc
, unsigned char *output
,
1146 unsigned int *output_len_p
, unsigned int max_output_len
,
1147 const unsigned char *input
, unsigned int input_len
,
1151 return SecCmsCipherContextCrypt(cc
, output
,
1152 output_len_p
, max_output_len
,
1156 int blocks
, bsize
, padlen
, pcount
, padsize
;
1157 unsigned int max_needed
, ifraglen
, ofraglen
, output_len
;
1158 unsigned char *pbuf
;
1161 PORT_Assert (cc
->encrypt
);
1164 * Check that we have enough room for the output. Our caller should
1165 * already handle this; failure is really an internal error (i.e. bug).
1167 max_needed
= SecCmsCipherContextEncryptLength (cc
, input_len
, final
);
1168 PORT_Assert (max_output_len
>= max_needed
);
1169 if (max_output_len
< max_needed
) {
1170 /* PORT_SetError (XXX); */
1174 bsize
= cc
->block_size
;
1175 padsize
= cc
->pad_size
;
1178 * When no blocking and padding work to do, we can simply call the
1179 * cipher function and we are done.
1182 return (*cc
->doit
)(cc
->cx
, output
, output_len_p
, max_output_len
,
1186 pcount
= cc
->pending_count
;
1187 pbuf
= cc
->pending_buf
;
1193 * Try to fill in an entire block, starting with the bytes
1194 * we already have saved away.
1196 while (input_len
&& pcount
< bsize
) {
1197 pbuf
[pcount
++] = *input
++;
1201 * If we do not have a full block and we know we will be
1202 * called again, then we are done for now.
1204 if (pcount
< bsize
&& !final
) {
1205 cc
->pending_count
= pcount
;
1206 if (output_len_p
!= NULL
)
1211 * If we have a whole block available, encrypt it.
1213 if ((padsize
== 0) || (pcount
% padsize
) == 0) {
1214 rv
= (* cc
->doit
) (cc
->cx
, output
, &ofraglen
, max_output_len
,
1216 if (rv
!= SECSuccess
)
1220 * For now anyway, all of our ciphers have the same number of
1221 * bytes of output as they do input. If this ever becomes untrue,
1222 * then sec_PKCS7EncryptLength needs to be made smarter!
1224 PORT_Assert (ofraglen
== pcount
);
1227 * Account for the bytes now in output.
1229 max_output_len
-= ofraglen
;
1230 output_len
+= ofraglen
;
1238 PORT_Assert (pcount
== 0);
1240 blocks
= input_len
/ bsize
;
1241 ifraglen
= blocks
* bsize
;
1244 rv
= (* cc
->doit
) (cc
->cx
, output
, &ofraglen
, max_output_len
,
1246 if (rv
!= SECSuccess
)
1250 * For now anyway, all of our ciphers have the same number of
1251 * bytes of output as they do input. If this ever becomes untrue,
1252 * then sec_PKCS7EncryptLength needs to be made smarter!
1254 PORT_Assert (ifraglen
== ofraglen
);
1256 max_output_len
-= ofraglen
;
1257 output_len
+= ofraglen
;
1261 pcount
= input_len
- ifraglen
;
1262 PORT_Assert (pcount
< bsize
);
1264 PORT_Memcpy (pbuf
, input
+ ifraglen
, pcount
);
1268 padlen
= padsize
- (pcount
% padsize
);
1269 PORT_Memset (pbuf
+ pcount
, padlen
, padlen
);
1270 rv
= (* cc
->doit
) (cc
->cx
, output
, &ofraglen
, max_output_len
,
1271 pbuf
, pcount
+padlen
);
1272 if (rv
!= SECSuccess
)
1276 * For now anyway, all of our ciphers have the same number of
1277 * bytes of output as they do input. If this ever becomes untrue,
1278 * then sec_PKCS7EncryptLength needs to be made smarter!
1280 PORT_Assert (ofraglen
== (pcount
+padlen
));
1281 output_len
+= ofraglen
;
1283 cc
->pending_count
= pcount
;
1286 PORT_Assert (output_len_p
!= NULL
|| output_len
== 0);
1287 if (output_len_p
!= NULL
)
1288 *output_len_p
= output_len
;