blob: 816c2347522b668b5c8748edfc37a56d47177d48 [file] [log] [blame]
Shawn Willden0a4df7e2014-08-28 16:09:05 -06001/*
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
23namespace keymaster {
24
25struct RSA_Delete {
26 void operator()(RSA* p) const { RSA_free(p); }
27};
28
29RsaOperation::~RsaOperation() {
30 if (rsa_key_ != NULL)
31 RSA_free(rsa_key_);
32}
33
34keymaster_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
44keymaster_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
51keymaster_error_t RsaSignOperation::Finish(const Buffer& /* signature */, Buffer* output) {
52 output->Reinitialize(RSA_size(rsa_key_));
53 if (data_.available_read() != output->buffer_size())
54 return KM_ERROR_INVALID_INPUT_LENGTH;
55
56 int bytes_encrypted = RSA_private_encrypt(data_.available_read(), data_.peek_read(),
57 output->peek_write(), rsa_key_, RSA_NO_PADDING);
58 if (bytes_encrypted < 0)
59 return KM_ERROR_UNKNOWN_ERROR;
60 assert(bytes_encrypted == RSA_size(rsa_key_));
61 output->advance_write(bytes_encrypted);
62 return KM_ERROR_OK;
63}
64
65keymaster_error_t RsaVerifyOperation::Finish(const Buffer& signature, Buffer* /* output */) {
66
67 if ((int)data_.available_read() != RSA_size(rsa_key_))
68 return KM_ERROR_INVALID_INPUT_LENGTH;
69 if (data_.available_read() != signature.available_read())
70 return KM_ERROR_VERIFICATION_FAILED;
71
72 UniquePtr<uint8_t[]> decrypted_data(new uint8_t[RSA_size(rsa_key_)]);
73 int bytes_decrypted = RSA_public_decrypt(signature.available_read(), signature.peek_read(),
74 decrypted_data.get(), rsa_key_, RSA_NO_PADDING);
75 if (bytes_decrypted < 0)
76 return KM_ERROR_UNKNOWN_ERROR;
77 assert(bytes_decrypted == RSA_size(rsa_key_));
78
79 if (memcmp_s(decrypted_data.get(), data_.peek_read(), data_.available_read()) == 0)
80 return KM_ERROR_OK;
81 return KM_ERROR_VERIFICATION_FAILED;
82}
83
84} // namespace keymaster