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 android.core;
18
19import android.security.MessageDigest;
20import android.test.suitebuilder.annotation.SmallTest;
21import junit.framework.TestCase;
22
23/**
24 * Tests SHA1 message digest algorithm.
25 */
26public class Sha1Test extends TestCase {
27    class TestData {
28        private String input;
29        private String result;
30
31        public TestData(String i, String r) {
32            input = i;
33            result = r;
34        }
35    }
36
37    TestData[] mTestData = new TestData[]{
38            new TestData("abc", "a9993e364706816aba3e25717850c26c9cd0d89d"),
39            new TestData("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
40                    "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
41    };
42
43    @SmallTest
44    public void testSha1() throws Exception {
45        MessageDigest digest = MessageDigest.getInstance("SHA-1");
46
47        int numTests = mTestData.length;
48        for (int i = 0; i < numTests; i++) {
49            digest.update(mTestData[i].input.getBytes());
50            byte[] hash = digest.digest();
51            String encodedHash = encodeHex(hash);
52            assertEquals(encodedHash, mTestData[i].result);
53        }
54    }
55
56    private static String encodeHex(byte[] bytes) {
57        StringBuffer hex = new StringBuffer(bytes.length * 2);
58
59        for (int i = 0; i < bytes.length; i++) {
60            if (((int) bytes[i] & 0xff) < 0x10) {
61                hex.append("0");
62            }
63            hex.append(Integer.toString((int) bytes[i] & 0xff, 16));
64        }
65
66        return hex.toString();
67    }
68}
69
70