1 /*
2 * Copyright 2014 The Android Open Source Project
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 <openssl/rsa.h>
18 #include <openssl/evp.h>
19
20 #include "rsa_operation.h"
21 #include "openssl_utils.h"
22
23 namespace keymaster {
24
25 struct RSA_Delete {
operator ()keymaster::RSA_Delete26 void operator()(RSA* p) const { RSA_free(p); }
27 };
28
~RsaOperation()29 RsaOperation::~RsaOperation() {
30 if (rsa_key_ != NULL)
31 RSA_free(rsa_key_);
32 }
33
Update(const Buffer & input,Buffer *)34 keymaster_error_t RsaOperation::Update(const Buffer& input, Buffer* /* output */) {
35 switch (purpose()) {
36 default:
37 return KM_ERROR_UNIMPLEMENTED;
38 case KM_PURPOSE_SIGN:
39 case KM_PURPOSE_VERIFY:
40 return StoreData(input);
41 }
42 }
43
StoreData(const Buffer & input)44 keymaster_error_t RsaOperation::StoreData(const Buffer& input) {
45 if (!data_.reserve(data_.available_read() + input.available_read()) ||
46 !data_.write(input.peek_read(), input.available_read()))
47 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
48 return KM_ERROR_OK;
49 }
50
Finish(const Buffer &,Buffer * output)51 keymaster_error_t RsaSignOperation::Finish(const Buffer& /* signature */, Buffer* output) {
52 output->Reinitialize(RSA_size(rsa_key_));
53 int bytes_encrypted = RSA_private_encrypt(data_.available_read(), data_.peek_read(),
54 output->peek_write(), rsa_key_, RSA_NO_PADDING);
55 if (bytes_encrypted < 0)
56 return KM_ERROR_UNKNOWN_ERROR;
57 assert(bytes_encrypted == RSA_size(rsa_key_));
58 output->advance_write(bytes_encrypted);
59 return KM_ERROR_OK;
60 }
61
Finish(const Buffer & signature,Buffer *)62 keymaster_error_t RsaVerifyOperation::Finish(const Buffer& signature, Buffer* /* output */) {
63
64 if ((int)data_.available_read() != RSA_size(rsa_key_))
65 return KM_ERROR_INVALID_INPUT_LENGTH;
66 if (data_.available_read() != signature.available_read())
67 return KM_ERROR_VERIFICATION_FAILED;
68
69 UniquePtr<uint8_t[]> decrypted_data(new uint8_t[RSA_size(rsa_key_)]);
70 int bytes_decrypted = RSA_public_decrypt(signature.available_read(), signature.peek_read(),
71 decrypted_data.get(), rsa_key_, RSA_NO_PADDING);
72 if (bytes_decrypted < 0)
73 return KM_ERROR_UNKNOWN_ERROR;
74 assert(bytes_decrypted == RSA_size(rsa_key_));
75
76 if (memcmp_s(decrypted_data.get(), data_.peek_read(), data_.available_read()) == 0)
77 return KM_ERROR_OK;
78 return KM_ERROR_VERIFICATION_FAILED;
79 }
80
81 } // namespace keymaster
82