Home | History | Annotate | Download | only in platform
      1 // Copyright 2014 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "config.h"
      6 #include "platform/Crypto.h"
      7 
      8 #include "public/platform/Platform.h"
      9 #include "public/platform/WebArrayBuffer.h"
     10 #include "public/platform/WebCrypto.h"
     11 #include "public/platform/WebCryptoAlgorithm.h"
     12 
     13 namespace blink {
     14 
     15 static blink::WebCryptoAlgorithmId toWebCryptoAlgorithmId(HashAlgorithm algorithm)
     16 {
     17     switch (algorithm) {
     18     case HashAlgorithmSha1:
     19         return blink::WebCryptoAlgorithmIdSha1;
     20     case HashAlgorithmSha256:
     21         return blink::WebCryptoAlgorithmIdSha256;
     22     case HashAlgorithmSha384:
     23         return blink::WebCryptoAlgorithmIdSha384;
     24     case HashAlgorithmSha512:
     25         return blink::WebCryptoAlgorithmIdSha512;
     26     };
     27 
     28     ASSERT_NOT_REACHED();
     29     return blink::WebCryptoAlgorithmIdSha256;
     30 }
     31 
     32 bool computeDigest(HashAlgorithm algorithm, const char* digestable, size_t length, DigestValue& digestResult)
     33 {
     34     blink::WebCryptoAlgorithmId algorithmId = toWebCryptoAlgorithmId(algorithm);
     35     blink::WebCrypto* crypto = blink::Platform::current()->crypto();
     36     unsigned char* result;
     37     unsigned resultSize;
     38 
     39     ASSERT(crypto);
     40 
     41     OwnPtr<blink::WebCryptoDigestor> digestor = adoptPtr(crypto->createDigestor(algorithmId));
     42     if (!digestor.get() || !digestor->consume(reinterpret_cast<const unsigned char*>(digestable), length) || !digestor->finish(result, resultSize))
     43         return false;
     44 
     45     digestResult.append(static_cast<uint8_t*>(result), resultSize);
     46     return true;
     47 }
     48 
     49 PassOwnPtr<blink::WebCryptoDigestor> createDigestor(HashAlgorithm algorithm)
     50 {
     51     return adoptPtr(blink::Platform::current()->crypto()->createDigestor(toWebCryptoAlgorithmId(algorithm)));
     52 }
     53 
     54 void finishDigestor(blink::WebCryptoDigestor* digestor, DigestValue& digestResult)
     55 {
     56     unsigned char* result = 0;
     57     unsigned resultSize = 0;
     58 
     59     if (!digestor->finish(result, resultSize))
     60         return;
     61 
     62     ASSERT(result);
     63 
     64     digestResult.append(static_cast<uint8_t*>(result), resultSize);
     65 }
     66 
     67 } // namespace blink
     68