pk11_des_unittest.cc 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim: set ts=2 et sw=2 tw=80: */
  3. /* This Source Code Form is subject to the terms of the Mozilla Public
  4. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  6. #include <memory>
  7. #include "nss.h"
  8. #include "pk11pub.h"
  9. #include "nss_scoped_ptrs.h"
  10. #include "gtest/gtest.h"
  11. namespace nss_test {
  12. class Pkcs11DesTest : public ::testing::Test {
  13. protected:
  14. SECStatus EncryptWithIV(std::vector<uint8_t>& iv,
  15. const CK_MECHANISM_TYPE mech) {
  16. // Generate a random key.
  17. ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
  18. ScopedPK11SymKey sym_key(
  19. PK11_KeyGen(slot.get(), mech, nullptr, 8, nullptr));
  20. EXPECT_TRUE(!!sym_key);
  21. std::vector<uint8_t> data(16);
  22. std::vector<uint8_t> output(16);
  23. SECItem params = {siBuffer, iv.data(),
  24. static_cast<unsigned int>(iv.size())};
  25. // Try to encrypt.
  26. unsigned int output_len = 0;
  27. return PK11_Encrypt(sym_key.get(), mech, &params, output.data(),
  28. &output_len, output.size(), data.data(), data.size());
  29. }
  30. };
  31. TEST_F(Pkcs11DesTest, ZeroLengthIV) {
  32. std::vector<uint8_t> iv(0);
  33. EXPECT_EQ(SECFailure, EncryptWithIV(iv, CKM_DES_CBC));
  34. EXPECT_EQ(SECFailure, EncryptWithIV(iv, CKM_DES3_CBC));
  35. }
  36. TEST_F(Pkcs11DesTest, IVTooShort) {
  37. std::vector<uint8_t> iv(7);
  38. EXPECT_EQ(SECFailure, EncryptWithIV(iv, CKM_DES_CBC));
  39. EXPECT_EQ(SECFailure, EncryptWithIV(iv, CKM_DES3_CBC));
  40. }
  41. TEST_F(Pkcs11DesTest, WrongLengthIV) {
  42. // We tolerate IVs > 8
  43. std::vector<uint8_t> iv(15, 0);
  44. EXPECT_EQ(SECSuccess, EncryptWithIV(iv, CKM_DES_CBC));
  45. EXPECT_EQ(SECSuccess, EncryptWithIV(iv, CKM_DES3_CBC));
  46. }
  47. TEST_F(Pkcs11DesTest, AllGood) {
  48. std::vector<uint8_t> iv(8, 0);
  49. EXPECT_EQ(SECSuccess, EncryptWithIV(iv, CKM_DES_CBC));
  50. EXPECT_EQ(SECSuccess, EncryptWithIV(iv, CKM_DES3_CBC));
  51. }
  52. } // namespace nss_test