1/*
2 * Copyright (C) 2013 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 com.android.verity;
18
19import java.security.PublicKey;
20import java.security.PrivateKey;
21import java.security.Security;
22import java.security.cert.X509Certificate;
23import org.bouncycastle.jce.provider.BouncyCastleProvider;
24
25public class VeritySigner {
26
27    private static void usage() {
28        System.err.println("usage: VeritySigner <contentfile> <key.pk8> " +
29                "<sigfile> | <contentfile> <certificate.x509.pem> <sigfile> " +
30                "-verify");
31        System.exit(1);
32    }
33
34    public static void main(String[] args) throws Exception {
35        if (args.length < 3) {
36            usage();
37            return;
38        }
39
40        Security.addProvider(new BouncyCastleProvider());
41
42        byte[] content = Utils.read(args[0]);
43
44        if (args.length > 3 && "-verify".equals(args[3])) {
45            X509Certificate cert = Utils.loadPEMCertificate(args[1]);
46            PublicKey publicKey = cert.getPublicKey();
47
48            byte[] signature = Utils.read(args[2]);
49
50            try {
51                if (Utils.verify(publicKey, content, signature,
52                            Utils.getSignatureAlgorithmIdentifier(publicKey))) {
53                    System.err.println("Signature is VALID");
54                    System.exit(0);
55                } else {
56                    System.err.println("Signature is INVALID");
57                }
58            } catch (Exception e) {
59                e.printStackTrace(System.err);
60            }
61
62            System.exit(1);
63        } else {
64            PrivateKey privateKey = Utils.loadDERPrivateKey(Utils.read(args[1]));
65            byte[] signature = Utils.sign(privateKey, content);
66            Utils.write(signature, args[2]);
67        }
68    }
69}
70