1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.bouncycastle.crypto.digests;
18
19import org.bouncycastle.crypto.ExtendedDigest;
20import org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi;
21import java.security.DigestException;
22import java.security.MessageDigest;
23
24/**
25 * Implements the BouncyCastle Digest interface using OpenSSL's EVP API. This
26 * must be an ExtendedDigest for {@link BcKeyStoreSpi} to be able to use it.
27 */
28public class OpenSSLDigest implements ExtendedDigest {
29    private final MessageDigest delegate;
30
31    private final int byteSize;
32
33    public OpenSSLDigest(String algorithm, int byteSize) {
34        try {
35            delegate = MessageDigest.getInstance(algorithm, "AndroidOpenSSL");
36            this.byteSize = byteSize;
37        } catch (Exception e) {
38            throw new RuntimeException(e);
39        }
40    }
41
42    public String getAlgorithmName() {
43        return delegate.getAlgorithm();
44    }
45
46    public int getDigestSize() {
47        return delegate.getDigestLength();
48    }
49
50    public int getByteLength() {
51        return byteSize;
52    }
53
54    public void reset() {
55        delegate.reset();
56    }
57
58    public void update(byte in) {
59        delegate.update(in);
60    }
61
62    public void update(byte[] in, int inOff, int len) {
63        delegate.update(in, inOff, len);
64    }
65
66    public int doFinal(byte[] out, int outOff) {
67        try {
68            return delegate.digest(out, outOff, out.length - outOff);
69        } catch (DigestException e) {
70            throw new RuntimeException(e);
71        }
72    }
73
74    public static class MD5 extends OpenSSLDigest {
75        public MD5() { super("MD5", 64); }
76    }
77
78    public static class SHA1 extends OpenSSLDigest {
79        public SHA1() { super("SHA-1", 64); }
80    }
81
82    public static class SHA224 extends OpenSSLDigest {
83        public SHA224() { super("SHA-224", 64); }
84    }
85
86    public static class SHA256 extends OpenSSLDigest {
87        public SHA256() { super("SHA-256", 64); }
88    }
89
90    public static class SHA384 extends OpenSSLDigest {
91        public SHA384() { super("SHA-384", 128); }
92    }
93
94    public static class SHA512 extends OpenSSLDigest {
95        public SHA512() { super("SHA-512", 128); }
96    }
97}
98