blob: 1da748e012be1456f314cf8a7252f07ecea42652 [file] [log] [blame]
Jeff Thompsonba16b8f2013-12-16 13:11:47 -08001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
2/**
3 * Copyright (C) 2013 Regents of the University of California.
4 * @author: Yingdi Yu <yingdi@cs.ucla.edu>
5 * See COPYING for copyright and distribution information.
6 */
7
8#include "../../c/util/crypto.h"
9#include <ndn-cpp/sha256-with-rsa-signature.hpp>
10#include <ndn-cpp/security/security-exception.hpp>
11#include <ndn-cpp/security/signature/sha256-with-rsa-handler.hpp>
12
13using namespace std;
Jeff Thompsonba16b8f2013-12-16 13:11:47 -080014
15namespace ndn {
16
17bool
Jeff Thompson2105dbe2013-12-18 16:16:28 -080018Sha256WithRsaHandler::verifySignature(const Data& data, const PublicKey& publicKey)
Jeff Thompsonba16b8f2013-12-16 13:11:47 -080019{
20 const Sha256WithRsaSignature *signature = dynamic_cast<const Sha256WithRsaSignature*>(data.getSignature());
21 if (!signature)
22 throw SecurityException("signature is not Sha256WithRsaSignature.");
23
24 // Set the data packet's default wire encoding if it is not already there.
25 if (signature->getDigestAlgorithm().size() != 0)
26 // TODO: Allow a non-default digest algorithm.
27 throw UnrecognizedDigestAlgorithmException("Cannot verify a data packet with a non-default digest algorithm.");
28 if (!data.getDefaultWireEncoding())
29 data.wireEncode();
30
31 // Set signedPortionDigest to the digest of the signed portion of the wire encoding.
32 uint8_t signedPortionDigest[SHA256_DIGEST_LENGTH];
33 ndn_digestSha256(data.getDefaultWireEncoding().signedBuf(), data.getDefaultWireEncoding().signedSize(), signedPortionDigest);
34
35 // Verify the signedPortionDigest.
36 // Use a temporary pointer since d2i updates it.
37 const uint8_t *derPointer = publicKey.getKeyDer().buf();
38 RSA *rsaPublicKey = d2i_RSA_PUBKEY(NULL, &derPointer, publicKey.getKeyDer().size());
39 if (!rsaPublicKey)
40 throw UnrecognizedKeyFormatException("Error decoding public key in d2i_RSAPublicKey");
41 int success = RSA_verify
42 (NID_sha256, signedPortionDigest, sizeof(signedPortionDigest), (uint8_t *)signature->getSignature().buf(),
43 signature->getSignature().size(), rsaPublicKey);
44 // Free the public key before checking for success.
45 RSA_free(rsaPublicKey);
46
47 // RSA_verify returns 1 for a valid signature.
48 return (success == 1);
49}
50
51}