libdigidocpp
RSASigner.cpp
Go to the documentation of this file.
1 /*
2  * libdigidocpp
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  *
18  */
19 
20 #include <string.h>
21 
22 #include <openssl/pem.h>
23 #include <openssl/err.h>
24 
25 #include "../../log.h"
26 #include "../../crypto/crypt/RSACrypt.h"
27 #include "RSASigner.h"
28 
29 
38 digidoc::RSASigner::RSASigner(X509* cert, RSA* privateKey) throw(SignException)
39  : cert(cert)
40  , privateKey(privateKey)
41 {
42  if(this->cert == NULL)
43  {
44  THROW_SIGNEXCEPTION("The provided X.509 certificate is NULL pointer.");
45  }
46 
47  if(this->privateKey == NULL)
48  {
49  THROW_SIGNEXCEPTION("The provided private RSA key is NULL pointer.");
50  }
51 }
52 
57 {
58 }
59 
67 {
68  DEBUG("RSASigner::getCert()");
69  return cert;
70 }
71 
81 void digidoc::RSASigner::sign(const Digest& digest, Signature& signature) throw(SignException)
82 {
83  DEBUG("RSASigner::sign(digest = {type=%s,digest=%p,length=%d}, signature={signature=%p,length=%d})",
84  OBJ_nid2sn(digest.type), digest.digest, digest.length, signature.signature, signature.length);
85 
86  try
87  {
88  // Sign the digest.
89  RSACrypt rsa(privateKey);
90  std::vector<unsigned char> sign = rsa.sign(digest);
91 
92  // Check that enough memory is allocated for the signature.
93  if(sign.size() > signature.length)
94  {
95  THROW_SIGNEXCEPTION("Not enough memory for signature allocated, needs %d bytes, allocated %d bytes.",
96  sign.size(), signature.length);
97  }
98 
99  // Copy the signature to the buffer.
100  memcpy(signature.signature, &sign[0], sign.size());
101  signature.length = (unsigned int)sign.size();
102  }
103  catch(const IOException& e)
104  {
105  THROW_SIGNEXCEPTION_CAUSE(e, "Failed to sign digest.");
106  }
107 }