1 // Copyright 2021 Google LLC
2 //
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 ///////////////////////////////////////////////////////////////////////////////
16
17 #include "tink/experimental/pqcrypto/signature/subtle/sphincs_sign.h"
18
19 #include <memory>
20 #include <string>
21 #include <utility>
22
23 #include "absl/memory/memory.h"
24 #include "absl/status/status.h"
25 #include "absl/strings/str_format.h"
26 #include "tink/experimental/pqcrypto/signature/subtle/sphincs_helper_pqclean.h"
27 #include "tink/experimental/pqcrypto/signature/subtle/sphincs_subtle_utils.h"
28 #include "tink/util/secret_data.h"
29 #include "tink/util/statusor.h"
30
31 namespace crypto {
32 namespace tink {
33 namespace subtle {
34
35 // static
New(SphincsPrivateKeyPqclean key)36 util::StatusOr<std::unique_ptr<PublicKeySign>> SphincsSign::New(
37 SphincsPrivateKeyPqclean key) {
38 auto status = internal::CheckFipsCompatibility<SphincsSign>();
39 if (!status.ok()) return status;
40
41 util::Status key_size = ValidatePrivateKeySize(key.GetKey().size());
42 if (!key_size.ok()) {
43 return key_size;
44 }
45
46 util::Status valid_parameters = ValidateParams(key.GetParams());
47 if (!valid_parameters.ok()) {
48 return valid_parameters;
49 }
50
51 return {absl::WrapUnique(new SphincsSign(std::move(key)))};
52 }
53
Sign(absl::string_view data) const54 util::StatusOr<std::string> SphincsSign::Sign(absl::string_view data) const {
55 util::StatusOr<int32_t> key_size_index =
56 SphincsKeySizeToIndex(key_.GetKey().size());
57 if (!key_size_index.ok()) {
58 return key_size_index.status();
59 }
60
61 size_t sig_length;
62 SphincsParamsPqclean params = key_.GetParams();
63 const SphincsHelperPqclean &sphincs_helper_pqclean =
64 GetSphincsHelperPqclean(params.hash_type, params.variant, *key_size_index,
65 params.sig_length_type);
66 std::string signature(sphincs_helper_pqclean.GetSignatureLength(), '0');
67
68 if ((sphincs_helper_pqclean.Sign(
69 reinterpret_cast<uint8_t *>(signature.data()), &sig_length,
70 reinterpret_cast<const uint8_t *>(data.data()), data.size(),
71 reinterpret_cast<const uint8_t *>(key_.GetKey().data())) != 0)) {
72 return util::Status(absl::StatusCode::kInternal, "Signing failed.");
73 }
74
75 return signature;
76 }
77
78 } // namespace subtle
79 } // namespace tink
80 } // namespace crypto
81