Java tutorial
/* * * * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package com.taobao.android.builder.tools.sign; import com.android.SdkConstants; import com.android.annotations.NonNull; import com.android.annotations.Nullable; import com.android.builder.signing.SigningException; import org.apache.commons.lang.StringUtils; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.DEROutputStream; import org.bouncycastle.cert.jcajce.JcaCertStore; import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.CMSProcessableByteArray; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSSignedDataGenerator; import org.bouncycastle.cms.CMSTypedData; import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.bouncycastle.util.encoders.Base64; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.security.DigestOutputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.Signature; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * ?? * Created by shenghua.nish on 2015-10-16 ?10:55. */ public class LocalSignedJarBuilder { private static final String DIGEST_ALGORITHM = "SHA1"; private static final String DIGEST_ATTR = "SHA1-Digest"; private static final String DIGEST_MANIFEST_ATTR = "SHA1-Digest-Manifest"; /** * Write to another stream and track how many bytes have been * written. */ private static class CountOutputStream extends FilterOutputStream { private int mCount = 0; public CountOutputStream(OutputStream out) { super(out); mCount = 0; } @Override public void write(int b) throws IOException { super.write(b); mCount++; } @Override public void write(byte[] b, int off, int len) throws IOException { super.write(b, off, len); mCount += len; } public int size() { return mCount; } } private JarOutputStream mOutputJar; private PrivateKey mKey; private X509Certificate mCertificate; private Manifest mManifest; private MessageDigest mMessageDigest; private String mSignFile; private byte[] mBuffer = new byte[4096]; /** * Classes which implement this interface provides a method to check whether a file should * be added to a Jar file. */ public interface IZipEntryFilter { /** * An exception thrown during packaging of a zip file into APK file. * This is typically thrown by implementations of * {@link IZipEntryFilter#checkEntry(String)}. */ public static class ZipAbortException extends Exception { private static final long serialVersionUID = 1L; public ZipAbortException() { super(); } public ZipAbortException(String format, Object... args) { super(String.format(format, args)); } public ZipAbortException(Throwable cause, String format, Object... args) { super(String.format(format, args), cause); } public ZipAbortException(Throwable cause) { super(cause); } } /** * Checks a file for inclusion in a Jar archive. * * @param archivePath the archive file path of the entry * @return <code>true</code> if the file should be included. * @throws ZipAbortException if writing the file should be aborted. */ public boolean checkEntry(String archivePath) throws ZipAbortException; } /** * Creates a {@link SignedJarBuilder} with a given output stream, and signing information. * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then * the archive will not be signed. * * @param out the {@link OutputStream} where to write the Jar archive. * @param key the {@link PrivateKey} used to sign the archive, or <code>null</code>. * @param certificate the {@link X509Certificate} used to sign the archive, or * <code>null</code>. * @throws IOException * @throws NoSuchAlgorithmException */ public LocalSignedJarBuilder(@NonNull OutputStream out, @Nullable PrivateKey key, @Nullable X509Certificate certificate, @Nullable String builtBy, @Nullable String createdBy, @Nullable String signFile) throws IOException, NoSuchAlgorithmException { mOutputJar = new JarOutputStream(new BufferedOutputStream(out)); mOutputJar.setLevel(9); mKey = key; mCertificate = certificate; mSignFile = signFile; if (mKey != null && mCertificate != null) { mManifest = new Manifest(); Attributes main = mManifest.getMainAttributes(); main.putValue("Manifest-Version", "1.0"); if (builtBy != null) { main.putValue("Built-By", builtBy); } if (createdBy != null) { main.putValue("Created-By", createdBy); } mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM); } } /** * Writes a new {@link File} into the archive. * * @param inputFile the {@link File} to write. * @param jarPath the filepath inside the archive. * @throws IOException */ public void writeFile(File inputFile, String jarPath) throws IOException { // Get an input stream on the file. FileInputStream fis = new FileInputStream(inputFile); try { // create the zip entry JarEntry entry = new JarEntry(jarPath); entry.setTime(inputFile.lastModified()); writeEntry(fis, entry); } finally { // close the file stream used to read the file fis.close(); } } private final byte[] buffer = new byte[8192]; /** * Copies the content of a Jar/Zip archive into the receiver archive. * <p/>An optional {@link IZipEntryFilter} allows to selectively choose which files * to copy over. * * @param input the {@link InputStream} for the Jar/Zip to copy. * @param filter the filter or <code>null</code> * @throws IOException * @throws SignedJarBuilder.IZipEntryFilter.ZipAbortException if the {@link IZipEntryFilter} filter indicated that the write * must be aborted. */ public void writeZip(InputStream input, IZipEntryFilter filter) throws IOException, IZipEntryFilter.ZipAbortException { ZipInputStream zis = new ZipInputStream(input); try { // loop on the entries of the intermediary package and put them in the final package. ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String name = entry.getName(); // do not take directories or anything inside a potential META-INF folder. if (entry.isDirectory()) { continue; } // ignore some of the content in META-INF/ but not all if (name.startsWith("META-INF/")) { // ignore the manifest file. String subName = name.substring(9); if ("MANIFEST.MF".equals(subName)) { int count; ByteArrayOutputStream out = new ByteArrayOutputStream(); while ((count = zis.read(buffer)) != -1) { out.write(buffer, 0, count); } ByteArrayInputStream swapStream = new ByteArrayInputStream(out.toByteArray()); Manifest manifest = new Manifest(swapStream); mManifest.getMainAttributes().putAll(manifest.getMainAttributes()); continue; } // special case for Maven meta-data because we really don't care about them in apks. if (name.startsWith("META-INF/maven/")) { continue; } // check for subfolder int index = subName.indexOf('/'); if (index == -1) { // no sub folder, ignores signature files. if (subName.endsWith(".SF") || name.endsWith(".RSA") || name.endsWith(".DSA")) { continue; } } } // if we have a filter, we check the entry against it if (filter != null && !filter.checkEntry(name)) { continue; } JarEntry newEntry; // Preserve the STORED method of the input entry. if (entry.getMethod() == JarEntry.STORED) { newEntry = new JarEntry(entry); } else { // Create a new entry so that the compressed len is recomputed. newEntry = new JarEntry(name); } writeEntry(zis, newEntry); zis.closeEntry(); } } finally { zis.close(); } } /** * Closes the Jar archive by creating the manifest, and signing the archive. * * @throws IOException * @throws SigningException */ public void close() throws IOException, SigningException { if (mManifest != null) { // write the manifest to the jar file mOutputJar.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME)); mManifest.write(mOutputJar); try { // CERT.SF Signature signature = Signature.getInstance("SHA1with" + mKey.getAlgorithm()); signature.initSign(mKey); if (StringUtils.isBlank(mSignFile)) { mOutputJar.putNextEntry(new JarEntry("META-INF/CERT.SF")); } else { mOutputJar.putNextEntry(new JarEntry("META-INF/" + mSignFile + ".SF")); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeSignatureFile(baos); byte[] signedData = baos.toByteArray(); mOutputJar.write(signedData); if (StringUtils.isBlank(mSignFile)) { mOutputJar.putNextEntry(new JarEntry("META-INF/CERT." + mKey.getAlgorithm())); } else { mOutputJar.putNextEntry(new JarEntry("META-INF/" + mSignFile + "." + mKey.getAlgorithm())); } // CERT.* writeSignatureBlock(new CMSProcessableByteArray(signedData), mCertificate, mKey); } catch (Exception e) { throw new SigningException(e); } } mOutputJar.close(); mOutputJar = null; } /** * Clean up of the builder for interrupted workflow. * This does nothing if {@link #close()} was called successfully. */ public void cleanUp() { if (mOutputJar != null) { try { mOutputJar.close(); } catch (IOException e) { // pass } } } /** * Adds an entry to the output jar, and write its content from the {@link InputStream} * * @param input The input stream from where to write the entry content. * @param entry the entry to write in the jar. * @throws IOException */ private void writeEntry(InputStream input, JarEntry entry) throws IOException { // add the entry to the jar archive mOutputJar.putNextEntry(entry); // read the content of the entry from the input stream, and write it into the archive. int count; while ((count = input.read(mBuffer)) != -1) { mOutputJar.write(mBuffer, 0, count); // update the digest if (mMessageDigest != null) { mMessageDigest.update(mBuffer, 0, count); } } // close the entry for this file mOutputJar.closeEntry(); if (mManifest != null) { // update the manifest for this entry. Attributes attr = mManifest.getAttributes(entry.getName()); if (attr == null) { attr = new Attributes(); mManifest.getEntries().put(entry.getName(), attr); } attr.putValue(DIGEST_ATTR, new String(Base64.encode(mMessageDigest.digest()), "ASCII")); } } /** * Writes a .SF file with a digest to the manifest. */ private void writeSignatureFile(OutputStream out) throws IOException, GeneralSecurityException { Manifest sf = new Manifest(); Attributes main = sf.getMainAttributes(); main.putValue("Signature-Version", "1.0"); main.putValue("Created-By", "1.0 (Android)"); MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM); PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, SdkConstants.UTF_8); // Digest of the entire manifest mManifest.write(print); print.flush(); main.putValue(DIGEST_MANIFEST_ATTR, new String(Base64.encode(md.digest()), "ASCII")); Map<String, Attributes> entries = mManifest.getEntries(); for (Map.Entry<String, Attributes> entry : entries.entrySet()) { // Digest of the manifest stanza for this entry. print.print("Name: " + entry.getKey() + "\r\n"); for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) { print.print(att.getKey() + ": " + att.getValue() + "\r\n"); } print.print("\r\n"); print.flush(); Attributes sfAttr = new Attributes(); sfAttr.putValue(DIGEST_ATTR, new String(Base64.encode(md.digest()), "ASCII")); sf.getEntries().put(entry.getKey(), sfAttr); } CountOutputStream cout = new CountOutputStream(out); sf.write(cout); // A bug in the java.util.jar implementation of Android platforms // up to version 1.6 will cause a spurious IOException to be thrown // if the length of the signature file is a multiple of 1024 bytes. // As a workaround, add an extra CRLF in this case. if ((cout.size() % 1024) == 0) { cout.write('\r'); cout.write('\n'); } } /** * Write the certificate file with a digital signature. */ private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(publicKey); JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm()) .build(privateKey); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) .setDirectSignature(true).build(sha1Signer, publicKey)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(data, false); ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded()); DEROutputStream dos = new DEROutputStream(mOutputJar); dos.writeObject(asn1.readObject()); dos.flush(); dos.close(); asn1.close(); } }