Botan 3.7.1
Crypto and TLS for C&
emsa_x931.cpp
Go to the documentation of this file.
1/*
2* EMSA_X931
3* (C) 1999-2007 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/internal/emsa_x931.h>
9
10#include <botan/exceptn.h>
11#include <botan/internal/fmt.h>
12#include <botan/internal/hash_id.h>
13#include <botan/internal/stl_util.h>
14
15namespace Botan {
16
17namespace {
18
19std::vector<uint8_t> emsa2_encoding(const std::vector<uint8_t>& msg,
20 size_t output_bits,
21 const std::vector<uint8_t>& empty_hash,
22 uint8_t hash_id) {
23 const size_t HASH_SIZE = empty_hash.size();
24
25 const size_t output_length = (output_bits + 1) / 8;
26
27 if(msg.size() != HASH_SIZE) {
28 throw Encoding_Error("EMSA_X931::encoding_of: Bad input length");
29 }
30 if(output_length < HASH_SIZE + 4) {
31 throw Encoding_Error("EMSA_X931::encoding_of: Output length is too small");
32 }
33
34 const bool empty_input = (msg == empty_hash);
35
36 std::vector<uint8_t> output(output_length);
37 BufferStuffer stuffer(output);
38
39 stuffer.append(empty_input ? 0x4B : 0x6B);
40 stuffer.append(0xBB, stuffer.remaining_capacity() - (1 + msg.size() + 2));
41 stuffer.append(0xBA);
42 stuffer.append(msg);
43 stuffer.append(hash_id);
44 stuffer.append(0xCC);
45 BOTAN_ASSERT_NOMSG(stuffer.full());
46
47 return output;
48}
49
50} // namespace
51
52std::string EMSA_X931::name() const {
53 return fmt("X9.31({})", m_hash->name());
54}
55
56void EMSA_X931::update(const uint8_t input[], size_t length) {
57 m_hash->update(input, length);
58}
59
60std::vector<uint8_t> EMSA_X931::raw_data() {
61 return m_hash->final_stdvec();
62}
63
64/*
65* EMSA_X931 Encode Operation
66*/
67std::vector<uint8_t> EMSA_X931::encoding_of(const std::vector<uint8_t>& msg,
68 size_t output_bits,
69 RandomNumberGenerator& /*rng*/) {
70 return emsa2_encoding(msg, output_bits, m_empty_hash, m_hash_id);
71}
72
73/*
74* EMSA_X931 Verify Operation
75*/
76bool EMSA_X931::verify(const std::vector<uint8_t>& coded, const std::vector<uint8_t>& raw, size_t key_bits) {
77 try {
78 return (coded == emsa2_encoding(raw, key_bits, m_empty_hash, m_hash_id));
79 } catch(...) {
80 return false;
81 }
82}
83
84/*
85* EMSA_X931 Constructor
86*/
87EMSA_X931::EMSA_X931(std::unique_ptr<HashFunction> hash) : m_hash(std::move(hash)) {
88 m_empty_hash = m_hash->final_stdvec();
89
90 m_hash_id = ieee1363_hash_id(m_hash->name());
91
92 if(!m_hash_id) {
93 throw Encoding_Error("EMSA_X931 no hash identifier for " + m_hash->name());
94 }
95}
96
97} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:59
EMSA_X931(std::unique_ptr< HashFunction > hash)
Definition emsa_x931.cpp:87
std::string name() const override
Definition emsa_x931.cpp:52
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
uint8_t ieee1363_hash_id(std::string_view name)
Definition hash_id.cpp:144