tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

pk11_des_unittest.cc (2013B)


      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 
      7 #include <memory>
      8 #include "nss.h"
      9 #include "pk11pub.h"
     10 
     11 #include "nss_scoped_ptrs.h"
     12 
     13 #include "gtest/gtest.h"
     14 
     15 namespace nss_test {
     16 
     17 class Pkcs11DesTest : public ::testing::Test {
     18 protected:
     19  SECStatus EncryptWithIV(std::vector<uint8_t>& iv,
     20                          const CK_MECHANISM_TYPE mech) {
     21    // Generate a random key.
     22    ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
     23    ScopedPK11SymKey sym_key(
     24        PK11_KeyGen(slot.get(), mech, nullptr, 8, nullptr));
     25    EXPECT_TRUE(!!sym_key);
     26 
     27    std::vector<uint8_t> data(16);
     28    std::vector<uint8_t> output(16);
     29 
     30    SECItem params = {siBuffer, iv.data(),
     31                      static_cast<unsigned int>(iv.size())};
     32 
     33    // Try to encrypt.
     34    unsigned int output_len = 0;
     35    return PK11_Encrypt(sym_key.get(), mech, &params, output.data(),
     36                        &output_len, output.size(), data.data(), data.size());
     37  }
     38 };
     39 
     40 TEST_F(Pkcs11DesTest, ZeroLengthIV) {
     41  std::vector<uint8_t> iv(0);
     42  EXPECT_EQ(SECFailure, EncryptWithIV(iv, CKM_DES_CBC));
     43  EXPECT_EQ(SECFailure, EncryptWithIV(iv, CKM_DES3_CBC));
     44 }
     45 
     46 TEST_F(Pkcs11DesTest, IVTooShort) {
     47  std::vector<uint8_t> iv(7);
     48  EXPECT_EQ(SECFailure, EncryptWithIV(iv, CKM_DES_CBC));
     49  EXPECT_EQ(SECFailure, EncryptWithIV(iv, CKM_DES3_CBC));
     50 }
     51 
     52 TEST_F(Pkcs11DesTest, WrongLengthIV) {
     53  // We tolerate IVs > 8
     54  std::vector<uint8_t> iv(15, 0);
     55  EXPECT_EQ(SECSuccess, EncryptWithIV(iv, CKM_DES_CBC));
     56  EXPECT_EQ(SECSuccess, EncryptWithIV(iv, CKM_DES3_CBC));
     57 }
     58 
     59 TEST_F(Pkcs11DesTest, AllGood) {
     60  std::vector<uint8_t> iv(8, 0);
     61  EXPECT_EQ(SECSuccess, EncryptWithIV(iv, CKM_DES_CBC));
     62  EXPECT_EQ(SECSuccess, EncryptWithIV(iv, CKM_DES3_CBC));
     63 }
     64 
     65 }  // namespace nss_test