1 /*
2  * @(#) $Id: CSR.java,v 1.3 2003/07/08 08:13:53 pankaj Exp $
3  *
4  * Copyright (c) 2002-03 by Pankaj Kumar (http://www.pankaj-k.net). 
5  * All rights reserved.
6  *
7  * The license governing the use of this file can be found in the 
8  * root directory of the containing software.
9  */
10package org.jstk.pki;
11
12import java.io.*;
13
14import org.jstk.asn1.*;
15import org.jstk.pem.*;
16import org.jstk.JSTKOptions;
17
18/*
19 * CSR ::= SEQUENCE {
20 *   csrInfo                CSRInfo,
21 *   algorithm              AlgorithmIdentifier,
22 *   signatureBytes     BIT STRING }
23 */
24public class CSR extends ASN1Seq{
25    private CSRInfo csrInfo = new CSRInfo();
26    private AlgorithmIdentifier algorithm = new AlgorithmIdentifier();
27    private ASN1BitString signatureBytes = new ASN1BitString();
28
29    public CSR(){
30        super();
31        add(csrInfo);
32        add(algorithm);
33        add(signatureBytes);
34    }
35
36    public CSRInfo getCSRInfo(){
37        return csrInfo;
38    }
39
40    public AlgorithmIdentifier getAlgorithm(){
41        return algorithm;
42    }
43
44    public ASN1BitString getSignatureBytes(){
45        return signatureBytes;
46    }
47
48    public String toString(){
49        StringBuffer sb = new StringBuffer();
50        sb.append("CSR-SEQ(" + csrInfo.toString() + ", ");
51        sb.append(algorithm.toString() + ", " + signatureBytes.toString() + ")");
52        return sb.toString();
53    }
54    public static void main(String[] args) throws Exception {
55        if (args.length < 1){
56            System.out.println("Usage::java CSR <file> [-encode <outfile>]");
57            return;
58        }
59        String file = args[0];
60        InputStream is = null;
61        try {                                       // Try PEM format
62            BufferedReader  reader = new BufferedReader(new FileReader(file));
63            PEMData x = new PEMData(reader);
64            is = new ByteArrayInputStream(x.decode());
65        } catch (InvalidPEMFormatException exc){    // Assume DER format
66            is = new FileInputStream(file);
67        }
68        DefASN1PullParser parser = new DefASN1PullParser();
69        parser.setInput(is);
70
71        CSR csr = new CSR();
72        csr.decode(parser);
73        System.out.println(csr.toString());
74
75        JSTKOptions opts = new JSTKOptions();
76        opts.parse(args, 1);
77        String outfile = opts.get("encode");
78        if (outfile != null){
79            System.out.println("Writing the data in DER format to file: " + outfile);
80            FileOutputStream fos = new FileOutputStream(outfile);
81            byte[] encoded = csr.encode();
82            fos.write(encoded);
83            fos.close();
84        }
85    }
86}
87
88