001: /*
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. See the NOTICE file distributed with
004: * this work for additional information regarding copyright ownership.
005: * The ASF licenses this file to You under the Apache License, Version 2.0
006: * (the "License"); you may not use this file except in compliance with
007: * the License. You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
013: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
014: * License for the specific language governing permissions and limitations under
015: * the License.
016: */
017:
018: package org.apache.harmony.tools.jarsigner;
019:
020: import java.io.IOException;
021: import java.io.InputStream;
022: import java.io.OutputStream;
023: import java.math.BigInteger;
024: import java.net.HttpURLConnection;
025: import java.net.InetSocketAddress;
026: import java.net.ProtocolException;
027: import java.net.Proxy;
028: import java.net.URI;
029: import java.net.URL;
030: import java.security.NoSuchAlgorithmException;
031: import java.security.SecureRandom;
032:
033: import org.apache.harmony.security.pkcs7.ContentInfo;
034: import org.apache.harmony.security.x509.AlgorithmIdentifier;
035: import org.apache.harmony.security.x509.tsp.MessageImprint;
036: import org.apache.harmony.security.x509.tsp.TimeStampReq;
037: import org.apache.harmony.security.x509.tsp.TimeStampResp;
038:
039: /**
040: * Class to generate time stamps.
041: */
042: class TimeStampGenerator {
043:
044: /**
045: * Generates a time-stamp request, sends it to the TSA, gets the response,
046: * decodes it and returns the TimeStampToken.
047: *
048: * @param digest
049: * @param algID
050: * @param tsaURI
051: * @param proxyAddr
052: * @param proxyPort
053: * @param proxyType
054: * @return
055: * @throws NoSuchAlgorithmException
056: * @throws IOException
057: */
058: static ContentInfo genTimeStamp(byte[] digest,
059: AlgorithmIdentifier algID, URI tsaURI, String proxyAddr,
060: int proxyPort, Proxy.Type proxyType)
061: throws NoSuchAlgorithmException, IOException {
062:
063: String errMsgAddrUsing = tsaURI
064: + " using "
065: + ((proxyAddr == null) ? "direct connection (no proxy)"
066: : proxyType + " proxy " + proxyAddr + ":"
067: + proxyPort);
068:
069: // create the time-stamp request
070: byte[] timeStampReq = generateTimeStampReq(digest, algID);
071:
072: // set up the connection to TSA server
073: HttpURLConnection conn;
074: InputStream in;
075: OutputStream out;
076: try {
077: conn = setConnection(tsaURI, proxyAddr, proxyPort,
078: proxyType, timeStampReq.length);
079: conn.connect();
080: in = conn.getInputStream();
081: out = conn.getOutputStream();
082: } catch (IOException e) {
083: String errMsg = "Cannot connect to " + errMsgAddrUsing;
084: throw (IOException) new IOException(errMsg).initCause(e);
085: }
086:
087: // send the request
088: try {
089: out.write(timeStampReq);
090: out.flush();
091: out.close();
092: } catch (IOException e) {
093: String errMsg = "Cannot post the request to "
094: + errMsgAddrUsing;
095: throw (IOException) new IOException(errMsg).initCause(e);
096: }
097:
098: // get the response
099: // byte buffer to contain the response from TSA
100: byte[] respBytes;
101: // total response length
102: int respLen = 0;
103: try {
104: // Time-stamp response is usually less than 8 Kbytes.
105: respBytes = new byte[8092];
106: // try to read the answer in several packets
107:
108: // length of the current chunk of data
109: int chunkLen = 0;
110: do {
111: int freeRespBytesSpace = respBytes.length - respLen;
112: chunkLen = in.read(respBytes, respLen,
113: freeRespBytesSpace);
114: if (chunkLen > 0) {
115: respLen += chunkLen;
116:
117: // if the respBytes buffer is full
118: if (chunkLen == freeRespBytesSpace) {
119: byte[] biggerBuffer = new byte[respBytes.length * 2];
120: System.arraycopy(respBytes, 0, biggerBuffer, 0,
121: respBytes.length);
122: respBytes = biggerBuffer;
123: }
124: }
125: } while (chunkLen > 0);
126: } catch (IOException e) {
127: String errMsg = "Cannot get response from "
128: + errMsgAddrUsing;
129: throw (IOException) new IOException(errMsg).initCause(e);
130: }
131: conn.disconnect();
132:
133: // return the decoded response or throw an IOException
134: return decodeResponse(respBytes, respLen);
135: }
136:
137: // generates a TimeStampReq and returns its ASN1 DER encoding
138: private static byte[] generateTimeStampReq(byte[] digest,
139: AlgorithmIdentifier algID) throws NoSuchAlgorithmException {
140: MessageImprint msgImprint = new MessageImprint(algID, digest);
141: SecureRandom random;
142: String randAlgName = "SHA1PRNG";
143: try {
144: random = SecureRandom.getInstance(randAlgName);
145: } catch (NoSuchAlgorithmException e) {
146: throw new NoSuchAlgorithmException("The algorithm "
147: + randAlgName
148: + " is not available in current environment.", e);
149: }
150: BigInteger nonce = BigInteger.valueOf(random.nextLong());
151: TimeStampReq req = new TimeStampReq(1, // version
152: msgImprint, // message imprint
153: null, // not asking for a particular policy
154: nonce, // nonce
155: Boolean.FALSE, // don't need the certificate inside the stamp
156: null); // no extensions
157: return req.getEncoded();
158: }
159:
160: // Creates a connection and sets up its properties,
161: // returns the created connection.
162: private static HttpURLConnection setConnection(URI tsaURI,
163: String proxyAddr, int proxyPort, Proxy.Type proxyType,
164: int contentLength) throws IOException {
165:
166: URL tsaURL = tsaURI.toURL();
167:
168: // FIXME: if proxy is not set!
169: InetSocketAddress proxyInetAddr = new InetSocketAddress(
170: proxyAddr, proxyPort);
171: Proxy proxy = new Proxy(proxyType, proxyInetAddr);
172: HttpURLConnection conn = (HttpURLConnection) tsaURL
173: .openConnection(proxy);
174: conn.setDoOutput(true);
175: conn.setDoInput(true);
176: try {
177: conn.setRequestMethod("POST");
178: } catch (ProtocolException e) {
179: // The exception cannot be thrown as it is thrown only if:
180: // - the method is called after the connection is set,
181: // - POST is not supported.
182: throw new RuntimeException("\"POST\" is not supported by "
183: + "the HTTP protocol implementation");
184: }
185: conn
186: .setRequestProperty("accept",
187: "application/timestamp-reply");
188: conn.setRequestProperty("content-type",
189: "application/timestamp-query");
190: conn.setRequestProperty("Content-Length", new String(""
191: + contentLength));
192: return conn;
193: }
194:
195: // decodes the response from TSA
196: private static ContentInfo decodeResponse(byte[] respBytes,
197: int respLen) throws IOException {
198: try {
199: TimeStampResp resp = (TimeStampResp) TimeStampResp.ASN1
200: .decode(respBytes, 0, respLen);
201: return resp.getTimeStampToken();
202: } catch (IOException e) {
203: // If failed to decode the response as a TimeStampResp,
204: // try to decode it as a TimeStampToken because some TSA-s
205: // return the token (not TimeStampResp) on success in spite
206: // of this conflicts with the RFC 3161.
207: try {
208: return (ContentInfo) ContentInfo.ASN1.decode(respBytes,
209: 0, respLen);
210: } catch (IOException ioe) {
211: String errMsg = "Cannot parse the response from TSA";
212: throw (IOException) new IOException(errMsg)
213: .initCause(e);
214: }
215: }
216: }
217: }
|