blob: 905fc3e3dd8c28b4e18793df95b0169cdc235750 [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;
14using namespace ndn::ptr_lib;
15
16namespace ndn {
17
18bool
19Sha256WithRsaHandler::verify(const Data& data, const PublicKey& publicKey)
20{
21 const Sha256WithRsaSignature *signature = dynamic_cast<const Sha256WithRsaSignature*>(data.getSignature());
22 if (!signature)
23 throw SecurityException("signature is not Sha256WithRsaSignature.");
24
25 // Set the data packet's default wire encoding if it is not already there.
26 if (signature->getDigestAlgorithm().size() != 0)
27 // TODO: Allow a non-default digest algorithm.
28 throw UnrecognizedDigestAlgorithmException("Cannot verify a data packet with a non-default digest algorithm.");
29 if (!data.getDefaultWireEncoding())
30 data.wireEncode();
31
32 // Set signedPortionDigest to the digest of the signed portion of the wire encoding.
33 uint8_t signedPortionDigest[SHA256_DIGEST_LENGTH];
34 ndn_digestSha256(data.getDefaultWireEncoding().signedBuf(), data.getDefaultWireEncoding().signedSize(), signedPortionDigest);
35
36 // Verify the signedPortionDigest.
37 // Use a temporary pointer since d2i updates it.
38 const uint8_t *derPointer = publicKey.getKeyDer().buf();
39 RSA *rsaPublicKey = d2i_RSA_PUBKEY(NULL, &derPointer, publicKey.getKeyDer().size());
40 if (!rsaPublicKey)
41 throw UnrecognizedKeyFormatException("Error decoding public key in d2i_RSAPublicKey");
42 int success = RSA_verify
43 (NID_sha256, signedPortionDigest, sizeof(signedPortionDigest), (uint8_t *)signature->getSignature().buf(),
44 signature->getSignature().size(), rsaPublicKey);
45 // Free the public key before checking for success.
46 RSA_free(rsaPublicKey);
47
48 // RSA_verify returns 1 for a valid signature.
49 return (success == 1);
50}
51
52}