Jeff Thompson | ba16b8f | 2013-12-16 13:11:47 -0800 | [diff] [blame] | 1 | /* -*- 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 | |
| 13 | using namespace std; |
Jeff Thompson | ba16b8f | 2013-12-16 13:11:47 -0800 | [diff] [blame] | 14 | |
| 15 | namespace ndn { |
| 16 | |
| 17 | bool |
Jeff Thompson | 2105dbe | 2013-12-18 16:16:28 -0800 | [diff] [blame] | 18 | Sha256WithRsaHandler::verifySignature(const Data& data, const PublicKey& publicKey) |
Jeff Thompson | ba16b8f | 2013-12-16 13:11:47 -0800 | [diff] [blame] | 19 | { |
| 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 | } |