pk11_cipherop_unittest.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // This Source Code Form is subject to the terms of the Mozilla Public
  2. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  3. // You can obtain one at http://mozilla.org/MPL/2.0/.
  4. #include "gtest/gtest.h"
  5. #include <assert.h>
  6. #include <limits.h>
  7. #include <prinit.h>
  8. #include <nss.h>
  9. #include <pk11pub.h>
  10. static const size_t kKeyLen = 128 / 8;
  11. namespace nss_test {
  12. //
  13. // The ciper tests using the bltest command cover a great deal of testing.
  14. // However, Bug 1489691 revealed a corner case which is covered here.
  15. // This test will make multiple calls to PK11_CipherOp using the same
  16. // cipher context with data that is not cipher block aligned.
  17. //
  18. static SECStatus GetBytes(PK11Context* ctx, uint8_t* bytes, size_t len) {
  19. std::vector<uint8_t> in(len, 0);
  20. int outlen;
  21. SECStatus rv = PK11_CipherOp(ctx, bytes, &outlen, len, &in[0], len);
  22. if (static_cast<size_t>(outlen) != len) {
  23. return SECFailure;
  24. }
  25. return rv;
  26. }
  27. TEST(Pkcs11CipherOp, SingleCtxMultipleUnalignedCipherOps) {
  28. PK11SlotInfo* slot;
  29. PK11SymKey* key;
  30. PK11Context* ctx;
  31. NSSInitContext* globalctx =
  32. NSS_InitContext("", "", "", "", NULL,
  33. NSS_INIT_READONLY | NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB |
  34. NSS_INIT_FORCEOPEN | NSS_INIT_NOROOTINIT);
  35. const CK_MECHANISM_TYPE cipher = CKM_AES_CTR;
  36. slot = PK11_GetInternalSlot();
  37. ASSERT_TRUE(slot);
  38. // Use arbitrary bytes for the AES key
  39. uint8_t key_bytes[kKeyLen];
  40. for (size_t i = 0; i < kKeyLen; i++) {
  41. key_bytes[i] = i;
  42. }
  43. SECItem keyItem = {siBuffer, key_bytes, kKeyLen};
  44. // The IV can be all zeros since we only encrypt once with
  45. // each AES key.
  46. CK_AES_CTR_PARAMS param = {128, {}};
  47. SECItem paramItem = {siBuffer, reinterpret_cast<unsigned char*>(&param),
  48. sizeof(CK_AES_CTR_PARAMS)};
  49. key = PK11_ImportSymKey(slot, cipher, PK11_OriginUnwrap, CKA_ENCRYPT,
  50. &keyItem, NULL);
  51. ctx = PK11_CreateContextBySymKey(cipher, CKA_ENCRYPT, key, &paramItem);
  52. ASSERT_TRUE(key);
  53. ASSERT_TRUE(ctx);
  54. uint8_t outbuf[128];
  55. ASSERT_EQ(GetBytes(ctx, outbuf, 7), SECSuccess);
  56. ASSERT_EQ(GetBytes(ctx, outbuf, 17), SECSuccess);
  57. PK11_FreeSymKey(key);
  58. PK11_FreeSlot(slot);
  59. PK11_DestroyContext(ctx, PR_TRUE);
  60. NSS_ShutdownContext(globalctx);
  61. }
  62. } // namespace nss_test