1 /* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 #include "password_ut.h" 16 #include "securec.h" 17 18 using namespace testing::ext; 19 namespace Hdc { 20 #define TEST_KEY_ALIAS "test_password_alias" SetUpTestCase()21 void HdcPasswordTest::SetUpTestCase() {} TearDownTestCase()22 void HdcPasswordTest::TearDownTestCase() {} SetUp()23 void HdcPasswordTest::SetUp() {} TearDown()24 void HdcPasswordTest::TearDown() {} 25 CheckPasswordFormat(std::pair<uint8_t *,int> pwdInfo)26 bool HdcPasswordTest::CheckPasswordFormat(std::pair<uint8_t*, int> pwdInfo) 27 { 28 std::string specialChar = "~!@#$%^&*()-_=+\\|[{}];:'\",<.>/?"; 29 if (pwdInfo.first == nullptr || pwdInfo.second != PASSWORD_LENGTH) { 30 return false; 31 } 32 33 if (specialChar.find(pwdInfo.first[0]) == std::string::npos) { 34 return false; 35 } 36 37 if (pwdInfo.first[1] < 'a' || pwdInfo.first[1] > 'z') { 38 return false; 39 } 40 for (int i = 2; i < pwdInfo.second; i++) { 41 if (pwdInfo.first[i] < '0' || pwdInfo.first[i] > '9') { 42 return false; 43 } 44 } 45 return true; 46 } 47 48 HWTEST_F(HdcPasswordTest, TestGeneratePassword, TestSize.Level0) 49 { 50 HdcPassword pwd(TEST_KEY_ALIAS); 51 pwd.GeneratePassword(); 52 std::pair<uint8_t*, int> pwdInfo = pwd.GetPassword(); 53 ASSERT_EQ(CheckPasswordFormat(pwdInfo), true); 54 } 55 56 HWTEST_F(HdcPasswordTest, TestGetEncryptPwdLength, TestSize.Level0) 57 { 58 // (12 bytes nonce value + 10 bytes pwd length + 16 bytes tag length ) * 2 (byte to hex) 59 #define ENCRYPT_LENGTH 76 60 HdcPassword pwd(TEST_KEY_ALIAS); 61 int len = pwd.GetEncryptPwdLength(); 62 ASSERT_EQ(len, ENCRYPT_LENGTH); 63 } 64 65 HWTEST_F(HdcPasswordTest, TestEncryptAndDecrypt, TestSize.Level0) 66 { 67 HdcPassword pwd(TEST_KEY_ALIAS); 68 std::pair<uint8_t*, int> plainPwd = pwd.GetPassword(); 69 (void)memset_s(plainPwd.first, plainPwd.second, '1', plainPwd.second); 70 ASSERT_EQ(pwd.ResetPwdKey(), true); 71 ASSERT_EQ(pwd.EncryptPwd(), true); 72 std::string encryptPwd = pwd.GetEncryptPassword(); 73 std::vector<uint8_t> encryptData(encryptPwd.data(), encryptPwd.data() + encryptPwd.length()); 74 ASSERT_EQ(pwd.DecryptPwd(encryptData), true); 75 plainPwd = pwd.GetPassword(); 76 ASSERT_EQ(memcmp(plainPwd.first, "1111111111", plainPwd.second), 0); 77 } 78 } // namespace Hdc