tor-browser

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

pk11_pbe_unittest.cc (2325B)


      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 "gtest/gtest.h"
     12 #include "nss_scoped_ptrs.h"
     13 
     14 namespace nss_test {
     15 
     16 static unsigned char* ToUcharPtr(std::string& str) {
     17  return const_cast<unsigned char*>(
     18      reinterpret_cast<const unsigned char*>(str.c_str()));
     19 }
     20 
     21 class Pkcs11PbeTest : public ::testing::Test {
     22 public:
     23  void Derive(std::vector<uint8_t>& derived) {
     24    // Shared between test vectors.
     25    const unsigned int kIterations = 4096;
     26    std::string pass("passwordPASSWORDpassword");
     27    std::string salt("saltSALTsaltSALTsaltSALTsaltSALTsalt");
     28 
     29    // Derivation must succeed with the right values.
     30    EXPECT_TRUE(DeriveBytes(pass, salt, derived, kIterations));
     31  }
     32 
     33 private:
     34  bool DeriveBytes(std::string& pass, std::string& salt,
     35                   std::vector<uint8_t>& derived, unsigned int kIterations) {
     36    SECItem pass_item = {siBuffer, ToUcharPtr(pass),
     37                         static_cast<unsigned int>(pass.length())};
     38    SECItem salt_item = {siBuffer, ToUcharPtr(salt),
     39                         static_cast<unsigned int>(salt.length())};
     40 
     41    // Set up PBE params.
     42    ScopedSECAlgorithmID alg_id(PK11_CreatePBEAlgorithmID(
     43        SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_2KEY_TRIPLE_DES_CBC, kIterations,
     44        &salt_item));
     45 
     46    // Derive.
     47    ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
     48    ScopedPK11SymKey sym_key(
     49        PK11_PBEKeyGen(slot.get(), alg_id.get(), &pass_item, false, nullptr));
     50 
     51    SECStatus rv = PK11_ExtractKeyValue(sym_key.get());
     52    EXPECT_EQ(rv, SECSuccess);
     53 
     54    SECItem* key_data = PK11_GetKeyData(sym_key.get());
     55 
     56    return key_data->len == derived.size() &&
     57           !memcmp(&derived[0], key_data->data, key_data->len);
     58  }
     59 };
     60 
     61 TEST_F(Pkcs11PbeTest, DeriveKnown) {
     62  std::vector<uint8_t> derived = {0x86, 0x6b, 0xce, 0xef, 0x26, 0xa4,
     63                                  0x4f, 0x02, 0x4a, 0x26, 0xcd, 0xd0,
     64                                  0x4f, 0x7c, 0x19, 0xad};
     65 
     66  Derive(derived);
     67 }
     68 
     69 }  // namespace nss_test