View Javadoc
1   /*
2    * Copyright 2012 Brian Matthews
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  
17  package com.btmatthews.maven.plugins.crx;
18  
19  import java.security.GeneralSecurityException;
20  import java.security.PrivateKey;
21  import java.security.PublicKey;
22  import java.security.Signature;
23  
24  import org.codehaus.plexus.component.annotations.Component;
25  
26  /**
27   * Implementation of {@link SignatureHelper} that signs a byte array using a public/private key pair.
28   *
29   * @author <a href="mailto:brian@btmatthews.com">Brian Matthews</a>
30   * @since 1.1.0
31   */
32  @Component(role = SignatureHelper.class, hint = "crx")
33  public class CRXSignatureHelper implements SignatureHelper {
34  
35      /**
36       * The algorithm used to generate the signature.
37       */
38      private static final String ALGORITHM = "SHA1withRSA";
39  
40      /**
41       * Generate the signature for a byte array using the private key.
42       *
43       * @param data The byte array.
44       * @param key  private key.
45       * @return The signature as a byte array.
46       * @throws GeneralSecurityException If there was a error generating the signature.
47       */
48      public byte[] sign(final byte[] data, final PrivateKey key) throws GeneralSecurityException {
49          final Signature signatureObject = Signature.getInstance(ALGORITHM);
50          signatureObject.initSign(key);
51          signatureObject.update(data);
52          return signatureObject.sign();
53      }
54  
55      /**
56       * Check that the signature is valid using the public key.
57       *
58       * @param data      The data for which the signature was generated.
59       * @param key       The public key.
60       * @param signature The signature.
61       * @return {@code true} if the signature was valid. Otherwise, {@code false}.
62       * @throws GeneralSecurityException If there was an error validating the signature.
63       */
64      public boolean check(final byte[] data, final PublicKey key, final byte[] signature) throws
65              GeneralSecurityException {
66          final Signature signatureObject = Signature.getInstance(ALGORITHM);
67          signatureObject.initVerify(key);
68          signatureObject.update(data);
69          return signatureObject.verify(signature);
70      }
71  }