|
12 | 12 |
|
13 | 13 | #include "mbedtls/config.h" |
14 | 14 | #include "PublicKey.hh" |
| 15 | +#include "SecureRandomize.hh" |
15 | 16 | #include "TLSContext.hh" |
16 | 17 | #include "Logging.hh" |
17 | 18 | #include "StringUtil.hh" |
@@ -78,11 +79,36 @@ namespace litecore { namespace crypto { |
78 | 79 | } |
79 | 80 |
|
80 | 81 |
|
| 82 | +#pragma mark - PUBLIC KEY: |
| 83 | + |
| 84 | + |
81 | 85 | PublicKey::PublicKey(slice data) { |
82 | 86 | parsePEMorDER(data, "public key", context(), &mbedtls_pk_parse_public_key); |
83 | 87 | } |
84 | 88 |
|
85 | 89 |
|
| 90 | + static int rngFunction(void *ctx, unsigned char *dst, size_t size) { |
| 91 | + SecureRandomize({dst, size}); |
| 92 | + return 0; |
| 93 | + } |
| 94 | + |
| 95 | + |
| 96 | + bool PublicKey::verifySignature(const SHA256 &inputDigest, slice signature) { |
| 97 | + int result = mbedtls_pk_verify(context(), |
| 98 | + MBEDTLS_MD_SHA256, // declares that input is a SHA256 digest. |
| 99 | + (const uint8_t*)inputDigest.asSlice().buf, |
| 100 | + inputDigest.asSlice().size, |
| 101 | + (const uint8_t*)signature.buf, signature.size); |
| 102 | + if (result == MBEDTLS_ERR_RSA_VERIFY_FAILED) |
| 103 | + return false; |
| 104 | + TRY(result); // other error codes throw exceptions |
| 105 | + return true; |
| 106 | + } |
| 107 | + |
| 108 | + |
| 109 | +#pragma mark - PRIVATE KEY: |
| 110 | + |
| 111 | + |
86 | 112 | PrivateKey::PrivateKey(slice data, slice password) { |
87 | 113 | if (password.size == 0) |
88 | 114 | password = nullslice; // interpret empty password as 'no password' |
@@ -123,7 +149,19 @@ namespace litecore { namespace crypto { |
123 | 149 | default: |
124 | 150 | Assert(false, "Invalid key format received (%d)", format); |
125 | 151 | } |
| 152 | + } |
| 153 | + |
126 | 154 |
|
| 155 | + alloc_slice PrivateKey::sign(const SHA256 &inputDigest) { |
| 156 | + alloc_slice signature(MBEDTLS_PK_SIGNATURE_MAX_SIZE); |
| 157 | + size_t sigLen = 0; |
| 158 | + TRY(mbedtls_pk_sign(context(), |
| 159 | + MBEDTLS_MD_SHA256, // declares that input is a SHA256 digest. |
| 160 | + (const uint8_t*)inputDigest.asSlice().buf, inputDigest.asSlice().size, |
| 161 | + (uint8_t*)signature.buf, &sigLen, |
| 162 | + rngFunction, nullptr)); |
| 163 | + signature.shorten(sigLen); |
| 164 | + return signature; |
127 | 165 | } |
128 | 166 |
|
129 | 167 |
|
|
0 commit comments