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; |
| 14 | using namespace ndn::ptr_lib; |
| 15 | |
| 16 | namespace ndn { |
| 17 | |
| 18 | bool |
| 19 | Sha256WithRsaHandler::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 | } |