1 /**
2 * Copyright 2021 Huawei Technologies Co., Ltd
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "fl/armour/secure_protocol/masking.h"
18
19 namespace mindspore {
20 namespace armour {
21 #ifdef _WIN32
GetMasking(std::vector<float> * noise,int noise_len,const uint8_t * seed,int seed_len,const uint8_t * ivec,int ivec_size)22 int Masking::GetMasking(std::vector<float> *noise, int noise_len, const uint8_t *seed, int seed_len,
23 const uint8_t *ivec, int ivec_size) {
24 MS_LOG(ERROR) << "Unsupported feature in Windows platform.";
25 return -1;
26 }
27
28 #else
29 int Masking::GetMasking(std::vector<float> *noise, int noise_len, const uint8_t *secret, int secret_len,
30 const uint8_t *ivec, int ivec_size) {
31 if ((secret_len != KEY_LENGTH_16 && secret_len != KEY_LENGTH_32) || secret == NULL) {
32 MS_LOG(ERROR) << "secret is invalid!";
33 return -1;
34 }
35 if (noise == NULL || noise_len <= 0) {
36 MS_LOG(ERROR) << "noise is invalid!";
37 return -1;
38 }
39 if (ivec == NULL || ivec_size != AES_IV_SIZE) {
40 MS_LOG(ERROR) << "ivec is invalid!";
41 return -1;
42 }
43 int size = noise_len * sizeof(int);
44 std::vector<uint8_t> data(size, 0);
45 std::vector<uint8_t> encrypt_data(size, 0);
46 int encrypt_len = 0;
47 AESEncrypt encrypt(secret, secret_len, ivec, AES_IV_SIZE, AES_CTR);
48 if (encrypt.EncryptData(data.data(), size, encrypt_data.data(), &encrypt_len) != 0) {
49 MS_LOG(ERROR) << "call AES-CTR failed!";
50 return -1;
51 }
52
53 for (int i = 0; i < noise_len; i++) {
54 auto value = *(reinterpret_cast<int32_t *>(encrypt_data.data()) + i);
55 noise->emplace_back(static_cast<float>(value) / INT32_MAX);
56 }
57 return 0;
58 }
59 #endif
60 } // namespace armour
61 } // namespace mindspore
62