util_b64_unittest.cc (2807B)
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 <climits> 8 #include <memory> 9 #include "nssb64.h" 10 11 #include "gtest/gtest.h" 12 #include "scoped_ptrs_util.h" 13 14 namespace nss_test { 15 16 class B64EncodeDecodeTest : public ::testing::Test { 17 public: 18 void TestDecodeStr(const std::string &str) { 19 ScopedSECItem tmp( 20 NSSBase64_DecodeBuffer(nullptr, nullptr, str.c_str(), str.size())); 21 ASSERT_TRUE(tmp); 22 char *out = NSSBase64_EncodeItem(nullptr, nullptr, 0, tmp.get()); 23 ASSERT_TRUE(out); 24 ASSERT_EQ(std::string(out), str); 25 PORT_Free(out); 26 } 27 bool TestEncodeItem(SECItem *item) { 28 bool rv = true; 29 char *out = NSSBase64_EncodeItem(nullptr, nullptr, 0, item); 30 rv = !!out; 31 if (out) { 32 ScopedSECItem tmp( 33 NSSBase64_DecodeBuffer(nullptr, nullptr, out, strlen(out))); 34 EXPECT_TRUE(tmp); 35 EXPECT_EQ(SECEqual, SECITEM_CompareItem(item, tmp.get())); 36 PORT_Free(out); 37 } 38 return rv; 39 } 40 bool TestFakeDecode(size_t str_len) { 41 std::string str(str_len, 'A'); 42 ScopedSECItem tmp( 43 NSSBase64_DecodeBuffer(nullptr, nullptr, str.c_str(), str.size())); 44 return !!tmp; 45 } 46 bool TestFakeEncode(size_t len) { 47 std::vector<uint8_t> data(len, 0x30); 48 SECItem tmp = {siBuffer, data.data(), 49 static_cast<unsigned int>(data.size())}; 50 return TestEncodeItem(&tmp); 51 } 52 53 protected: 54 }; 55 56 TEST_F(B64EncodeDecodeTest, DecEncTest) { TestDecodeStr("VGhpcyBpcyBOU1Mh"); } 57 58 TEST_F(B64EncodeDecodeTest, EncDecTest) { 59 uint8_t data[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09}; 60 SECItem tmp = {siBuffer, data, sizeof(data)}; 61 TestEncodeItem(&tmp); 62 } 63 64 TEST_F(B64EncodeDecodeTest, IncompleteData) { 65 NSSBase64Decoder *context = NSSBase64Decoder_Create( 66 [](void *, const unsigned char *, PRInt32) { return 0; }, nullptr); 67 EXPECT_TRUE(!!context); 68 char data = 'A'; 69 EXPECT_EQ(SECSuccess, NSSBase64Decoder_Update(context, &data, 1)); 70 EXPECT_EQ(SECFailure, NSSBase64Decoder_Destroy(context, false)); 71 } 72 73 TEST_F(B64EncodeDecodeTest, FakeDecTest) { EXPECT_TRUE(TestFakeDecode(100)); } 74 75 TEST_F(B64EncodeDecodeTest, FakeEncDecTest) { 76 EXPECT_TRUE(TestFakeEncode(100)); 77 } 78 79 // These takes a while ... 80 TEST_F(B64EncodeDecodeTest, DISABLED_LongFakeDecTest1) { 81 EXPECT_TRUE(TestFakeDecode(0x66666666)); 82 } 83 TEST_F(B64EncodeDecodeTest, DISABLED_LongFakeEncDecTest1) { 84 TestFakeEncode(0x3fffffff); 85 } 86 TEST_F(B64EncodeDecodeTest, DISABLED_LongFakeEncDecTest2) { 87 EXPECT_FALSE(TestFakeEncode(0x40000000)); 88 } 89 90 } // namespace nss_test