1 // Copyright 2023 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/signature/ed25519_private_key.h"
18
19 #include "openssl/crypto.h"
20 #include "tink/insecure_secret_key_access.h"
21 #include "tink/internal/ec_util.h"
22 #include "tink/partial_key_access_token.h"
23 #include "tink/util/secret_data.h"
24
25 namespace crypto {
26 namespace tink {
27
Create(const Ed25519PublicKey & public_key,const RestrictedData & private_key_bytes,PartialKeyAccessToken token)28 util::StatusOr<Ed25519PrivateKey> Ed25519PrivateKey::Create(
29 const Ed25519PublicKey& public_key, const RestrictedData& private_key_bytes,
30 PartialKeyAccessToken token) {
31 if (private_key_bytes.size() != 32) {
32 return util::Status(absl::StatusCode::kInvalidArgument,
33 "Ed25519 private key length must be 32 bytes.");
34 }
35 // Confirm that private key and public key are a valid Ed25519 key pair.
36 util::StatusOr<std::unique_ptr<internal::Ed25519Key>> key_pair =
37 internal::NewEd25519Key(util::SecretDataFromStringView(
38 private_key_bytes.GetSecret(InsecureSecretKeyAccess::Get())));
39 absl::string_view expected_public_key = public_key.GetPublicKeyBytes(token);
40 if (CRYPTO_memcmp(expected_public_key.data(), (*key_pair)->public_key.data(),
41 32) != 0) {
42 return util::Status(absl::StatusCode::kInvalidArgument,
43 "Invalid public key for private key bytes.");
44 }
45 return Ed25519PrivateKey(public_key, private_key_bytes);
46 }
47
operator ==(const Key & other) const48 bool Ed25519PrivateKey::operator==(const Key& other) const {
49 const Ed25519PrivateKey* that =
50 dynamic_cast<const Ed25519PrivateKey*>(&other);
51 if (that == nullptr) {
52 return false;
53 }
54 if (public_key_ != that->public_key_) {
55 return false;
56 }
57 return private_key_bytes_ == that->private_key_bytes_;
58 }
59
60 } // namespace tink
61 } // namespace crypto
62