001 /**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one or more
004 * contributor license agreements. See the NOTICE file distributed with
005 * this work for additional information regarding copyright ownership.
006 * The ASF licenses this file to You under the Apache License, Version 2.0
007 * (the "License"); you may not use this file except in compliance with
008 * the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018 package org.apache.geronimo.crypto;
019
020 import java.io.BufferedReader;
021 import java.io.ByteArrayInputStream;
022 import java.io.ByteArrayOutputStream;
023 import java.io.FileOutputStream;
024 import java.io.IOException;
025 import java.io.InputStreamReader;
026 import java.io.OutputStream;
027 import java.io.PrintWriter;
028 import java.security.InvalidKeyException;
029 import java.security.KeyFactory;
030 import java.security.NoSuchAlgorithmException;
031 import java.security.NoSuchProviderException;
032 import java.security.PublicKey;
033 import java.security.Signature;
034 import java.security.SignatureException;
035 import java.security.cert.Certificate;
036 import java.security.cert.CertificateEncodingException;
037 import java.security.spec.RSAPublicKeySpec;
038 import java.util.HashMap;
039 import java.util.Hashtable;
040 import java.util.Map;
041 import java.util.Vector;
042
043 import javax.security.auth.x500.X500Principal;
044
045 import org.apache.geronimo.crypto.asn1.ASN1InputStream;
046 import org.apache.geronimo.crypto.asn1.ASN1Sequence;
047 import org.apache.geronimo.crypto.asn1.DERBitString;
048 import org.apache.geronimo.crypto.asn1.DERObject;
049 import org.apache.geronimo.crypto.asn1.DERSequence;
050 import org.apache.geronimo.crypto.asn1.DERString;
051 import org.apache.geronimo.crypto.asn1.pkcs.CertificationRequestInfo;
052 import org.apache.geronimo.crypto.asn1.pkcs.PKCSObjectIdentifiers;
053 import org.apache.geronimo.crypto.asn1.x509.RSAPublicKeyStructure;
054 import org.apache.geronimo.crypto.asn1.x509.SubjectPublicKeyInfo;
055 import org.apache.geronimo.crypto.asn1.x509.X509CertificateStructure;
056 import org.apache.geronimo.crypto.asn1.x509.X509Name;
057 import org.apache.geronimo.crypto.encoders.Base64;
058 import org.apache.geronimo.crypto.jce.PKCS10CertificationRequest;
059
060 /**
061 * This class implements some utility methods used by CA
062 *
063 * @version $Rev: 706640 $ $Date: 2008-10-21 14:44:05 +0000 (Tue, 21 Oct 2008) $
064 */
065 public class CaUtils {
066 public static final String CERT_HEADER = "-----BEGIN CERTIFICATE-----";
067 public static final String CERT_FOOTER = "-----END CERTIFICATE-----";
068 public static final String CERT_REQ_HEADER = "-----BEGIN CERTIFICATE REQUEST-----";
069 public static final String CERT_REQ_FOOTER = "-----END CERTIFICATE REQUEST-----";
070 public static final int B64_LINE_SIZE = 76;
071 public static final String CERT_REQ_SUBJECT = "subject";
072 public static final String CERT_REQ_PUBLICKEY = "publickey";
073 public static final String CERT_REQ_PUBLICKEY_OBJ = "publickeyObj";
074 public static final String CERT_REQ_VERSION = "version";
075 public static final String PKAC_CHALLENGE = "challenge";
076
077 /**
078 * This method returns base64 encoded text of a given certificate.
079 * @param cert The certificate that needs to be encoded in base64
080 */
081 public static String base64Certificate(Certificate cert) throws CertificateEncodingException, Exception {
082 return base64Text(cert.getEncoded(), CaUtils.CERT_HEADER, CaUtils.CERT_FOOTER, CaUtils.B64_LINE_SIZE);
083 }
084
085 /**
086 * This method encodes a given byte array into base64 along with specified header and footers.
087 * @param data The byte array to be encoded in base64
088 * @param header Header for base64 encoded text
089 * @param footer Footer for base64 encoded text
090 * @param lineSize Maximum line size to split base64 encoded text if required
091 */
092 public static String base64Text(byte[] data, String header, String footer, int lineSize) throws Exception {
093 ByteArrayOutputStream bout = new ByteArrayOutputStream();
094 storeInBase64(bout, data, header, footer, lineSize);
095 bout.close();
096 return bout.toString();
097 }
098 /**
099 * This method encodes a given byte array into base64 along with specified header and footers and writes
100 * the output to a specified OutputStream.
101 * @param fout Output stream to write the encoded text
102 * @param data The byte array to be encoded in base64
103 * @param header Header for base64 encoded text
104 * @param footer Footer for base64 encoded text
105 * @param lineSize Maximum line size to split base64 encoded text if required
106 */
107 public static void storeInBase64(OutputStream fout, byte[] data, String header, String footer, int lineSize) throws Exception {
108 PrintWriter out = new PrintWriter(fout);
109 if(header != null) out.println(header);
110
111 byte[] encodedData = Base64.encode(data);
112 int i = 0;
113 do {
114 out.println(new String(encodedData, i, Math.min(lineSize, encodedData.length-i)));
115 i += lineSize;
116 } while(i < encodedData.length);
117
118 if(footer != null) out.println(footer);
119 out.flush();
120 }
121
122 /**
123 * This method encodes a given byte array into base64 along with specified header and footers and writes
124 * the output to a specified file.
125 * @param outfile File name to write the output to
126 * @param data The byte array to be encoded in base64
127 * @param header Header for base64 encoded text
128 * @param footer Footer for base64 encoded text
129 * @param lineSize Maximum line size to split base64 encoded text if required
130 */
131 public static void storeInBase64(String outfile, byte[] data, String header, String footer, int lineSize) throws Exception {
132 FileOutputStream fout = new FileOutputStream(outfile);
133 storeInBase64(fout, data, header, footer, lineSize);
134 fout.close();
135 }
136
137 /**
138 * This method creates a java.security.PublicKey object based on the public key information given in SubjectPublicKeyInfo
139 * @param pubKeyInfo SubjectPublicKeyInfo instance containing the public key information.
140 */
141 public static PublicKey getPublicKeyObject(SubjectPublicKeyInfo pubKeyInfo) throws Exception{
142 RSAPublicKeyStructure pubkeyStruct = new RSAPublicKeyStructure((ASN1Sequence)pubKeyInfo.getPublicKey());
143 RSAPublicKeySpec pubkeySpec = new RSAPublicKeySpec(pubkeyStruct.getModulus(), pubkeyStruct.getPublicExponent());
144 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
145 PublicKey pubKey = keyFactory.generatePublic(pubkeySpec);
146 return pubKey;
147 }
148
149 /**
150 * This method returns a X509Name object corresponding to the subject in a given certificate
151 * @param cert Certificate from which subject needs to be retrieved
152 */
153 public static X509Name getSubjectX509Name(Certificate cert) throws CertificateEncodingException, IOException {
154 ASN1InputStream ais = new ASN1InputStream(cert.getEncoded());
155 X509CertificateStructure x509Struct = new X509CertificateStructure((ASN1Sequence)ais.readObject());
156 ais.close();
157 return x509Struct.getSubject();
158 }
159
160 /**
161 * This method returns a X509Name object corresponding to a given principal
162 */
163 public static X509Name getX509Name(X500Principal principal) throws CertificateEncodingException, IOException {
164 ASN1InputStream ais = new ASN1InputStream(principal.getEncoded());
165 X509Name name = new X509Name((ASN1Sequence)ais.readObject());
166 ais.close();
167 return name;
168 }
169
170 /**
171 * This method processes a certificate request and returns a map containing subject
172 * and public key in the request.
173 * @param certreq base64 encoded PKCS10 certificate request
174 */
175 public static Map processPKCS10Request(String certreq) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, Exception {
176 if(certreq.indexOf("-----") != -1) {
177 // Strip any header and footer
178 BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(certreq.getBytes())));
179 String line = null;
180 String b64data = "";
181 while((line = br.readLine()) != null) {
182 if(!line.startsWith("-----")) {
183 b64data += line;
184 }
185 }
186 br.close();
187 certreq = b64data;
188 }
189 byte[] data = Base64.decode(certreq);
190
191 PKCS10CertificationRequest pkcs10certreq = new PKCS10CertificationRequest(data);
192 if(!pkcs10certreq.verify()) {
193 throw new Exception("CSR verification failed.");
194 }
195 CertificationRequestInfo certReqInfo = pkcs10certreq.getCertificationRequestInfo();
196 Map map = new HashMap();
197 map.put(CERT_REQ_SUBJECT, certReqInfo.getSubject());
198 map.put(CERT_REQ_PUBLICKEY, certReqInfo.getSubjectPublicKeyInfo());
199 map.put(CERT_REQ_PUBLICKEY_OBJ, getPublicKeyObject(certReqInfo.getSubjectPublicKeyInfo()));
200 map.put(CERT_REQ_VERSION, certReqInfo.getVersion());
201 return map;
202 }
203
204 /**
205 * This method processes a DER encoded SignedPublicKeyAndChallenge in base64 format.
206 * @param spkac SignedPublicKeyAndChallenge in base64 text format
207 * @return a Map with Subject, public-key and challenge
208 */
209 public static Map processSPKAC(String spkac) throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, Exception {
210 Map map = new HashMap();
211 byte[]data = Base64.decode(spkac);
212 ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(data));
213 DERSequence spkacSeq = (DERSequence)ais.readObject();
214
215 // SPKAC = SEQ {PKAC, SIGN-ALG, SIGN}
216 // Get PKAC and obtain PK and C
217 DERSequence pkacSeq = (DERSequence)spkacSeq.getObjectAt(0);
218 DERObject pk = (DERObject)pkacSeq.getObjectAt(0);
219 DERObject ch = (DERObject)pkacSeq.getObjectAt(1);
220 SubjectPublicKeyInfo pkInfo = new SubjectPublicKeyInfo((DERSequence)pk);
221 PublicKey pubKey = getPublicKeyObject(pkInfo);
222
223 // Get SIGN-ALG
224 DERSequence signAlg = (DERSequence) spkacSeq.getObjectAt(1);
225 DERObject alg0 = (DERObject)signAlg.getObjectAt(0);
226
227 // Get SIGN
228 DERBitString sign = (DERBitString) spkacSeq.getObjectAt(2);
229 byte[] signature = sign.getBytes();
230
231 // Verify the signature on SPKAC
232 String signAlgString = PKCSObjectIdentifiers.md5WithRSAEncryption.equals(alg0) ? "MD5withRSA" :
233 PKCSObjectIdentifiers.md2WithRSAEncryption.equals(alg0) ? "MD2withRSA" :
234 PKCSObjectIdentifiers.sha1WithRSAEncryption.equals(alg0) ? "SHA1withRSA" : null;
235 Signature signObj = Signature.getInstance(signAlgString);
236 signObj.initVerify(pubKey);
237 signObj.update(pkacSeq.getEncoded());
238 boolean verified = signObj.verify(signature);
239 if(!verified) throw new Exception("SignedPublicKeyAndChallenge verification failed.");
240 map.put(CERT_REQ_PUBLICKEY, pkInfo);
241 map.put(CERT_REQ_PUBLICKEY_OBJ, pubKey);
242 if(((DERString)ch).getString() != null) map.put(PKAC_CHALLENGE, ((DERString)ch).getString());
243 return map;
244 }
245
246 /**
247 * This method creates a X509Name object using the name attributes specified.
248 * @param cn Common Name
249 * @param ou Organization Unit
250 * @param o Organization
251 * @param l Locality
252 * @param st State
253 * @param c Country
254 */
255 public static X509Name getX509Name(String cn, String ou, String o, String l, String st, String c) {
256 Vector order = new Vector();
257 Hashtable attrmap = new Hashtable();
258 if (c != null) {
259 attrmap.put(X509Name.C, c);
260 order.add(X509Name.C);
261 }
262
263 if (st != null) {
264 attrmap.put(X509Name.ST, st);
265 order.add(X509Name.ST);
266 }
267
268 if (l != null) {
269 attrmap.put(X509Name.L, l);
270 order.add(X509Name.L);
271 }
272
273 if (o != null) {
274 attrmap.put(X509Name.O, o);
275 order.add(X509Name.O);
276 }
277
278 if (ou != null) {
279 attrmap.put(X509Name.OU, ou);
280 order.add(X509Name.OU);
281 }
282
283 if (cn != null) {
284 attrmap.put(X509Name.CN, cn);
285 order.add(X509Name.CN);
286 }
287
288 return new X509Name(order, attrmap);
289 }
290 }