Example usage for java.security Signature getInstance

List of usage examples for java.security Signature getInstance

Introduction

In this page you can find the example usage for java.security Signature getInstance.

Prototype

public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Closes the Jar archive by creating the manifest, and signing the archive.
 *
 * @throws IOException/*from   w ww. java 2s .c o  m*/
 * @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;
}

From source file:org.signserver.module.mrtdsodsigner.MRTDSODSigner.java

static byte[] getSampleSignedData(byte[] dataToBeSigned, PrivateKey privateKey)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    byte[] encryptedDigest = null;

    Signature s = null;//from  w  w w . ja  v a  2s  .c o  m
    s = Signature.getInstance("SHA256withRSA");
    s.initSign(privateKey);
    s.update(dataToBeSigned);
    encryptedDigest = s.sign();
    return encryptedDigest;
}

From source file:com.vmware.identity.SharedUtils.java

/**
 * Produce a string with signature/*from   w  ww.  j a  va  2  s.  c  o m*/
 *
 * @param privateKey
 * @param relayStateParameter
 * @param samlRequestParameter
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws SignatureException
 */
public static String getSamlRequestSignature(PrivateKey privateKey, String relayStateParameter,
        String samlRequestParameter)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, SignatureException {
    // produce signature
    SignatureAlgorithm algo = SignatureAlgorithm.getSignatureAlgorithmForURI(TestConstants.SIGNATURE_ALGORITHM);
    Signature sig = Signature.getInstance(algo.getAlgorithmName());
    sig.initSign(privateKey);

    String messageToSign = Shared.SAML_REQUEST_PARAMETER + "="
            + URLEncoder.encode(samlRequestParameter, "UTF-8") + "&" + Shared.RELAY_STATE_PARAMETER + "="
            + URLEncoder.encode(relayStateParameter, "UTF-8") + "&" + Shared.SIGNATURE_ALGORITHM_PARAMETER + "="
            + URLEncoder.encode(algo.toString(), "UTF-8");

    byte[] messageBytes = messageToSign.getBytes();
    sig.update(messageBytes);

    byte[] sigBytes = sig.sign();
    String signature = Shared.encodeBytes(sigBytes);
    return signature;
}

From source file:org.openbravo.erpCommon.obps.ActivationKey.java

private boolean decrypt(byte[] bytes, PublicKey pk, ByteArrayOutputStream bos, String strOBPublicKey)
        throws Exception {
    PublicKey obPk = getPublicKey(strOBPublicKey); // get OB public key to check signature
    Signature signer = Signature.getInstance("MD5withRSA");
    signer.initVerify(obPk);/*  ww  w .  j a v  a  2  s .co m*/

    Cipher cipher = Cipher.getInstance("RSA");

    ByteArrayInputStream bis = new ByteArrayInputStream(
            org.apache.commons.codec.binary.Base64.decodeBase64(bytes));

    // Encryptation only accepts 128B size, it must be chuncked
    final byte[] buf = new byte[128];
    final byte[] signature = new byte[128];

    // read the signature
    if (!(bis.read(signature) > 0)) {
        return false;
    }

    // decrypt
    while ((bis.read(buf)) > 0) {
        cipher.init(Cipher.DECRYPT_MODE, pk);
        bos.write(cipher.doFinal(buf));
    }

    // verify signature
    signer.update(bos.toByteArray());
    boolean signed = signer.verify(signature);
    log.debug("signature length:" + buf.length);
    log.debug("singature:" + (new BigInteger(signature).toString(16).toUpperCase()));
    log.debug("signed:" + signed);
    if (!signed) {
        isActive = false;
        errorMessage = "@NotSigned@";
        setLogger();
        return false;
    }
    return true;
}

From source file:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java

@Test
public void testInvalidAuthenticationSignature() throws Exception {
    // setup/*w w  w  .jav  a 2 s  .com*/
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    String userId = "1234";
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(),
            "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null,
            null);

    byte[] salt = "salt".getBytes();
    byte[] sessionId = "session-id".getBytes();

    AuthenticationDataMessage message = new AuthenticationDataMessage();
    message.authnCert = certificate;
    message.saltValue = salt;
    message.sessionId = sessionId;

    Map<String, String> httpHeaders = new HashMap<String, String>();
    HttpSession testHttpSession = new HttpTestSession();
    HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class);
    ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class);

    AuthenticationChallenge.generateChallenge(testHttpSession);

    AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId,
            null, "foobar-challenge".getBytes());
    byte[] toBeSigned = authenticationContract.calculateToBeSigned();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(keyPair.getPrivate());
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuthenticationTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuditTestService.class.getName());
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class"))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class"))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(
            AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(null);

    EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session"))
            .andStubReturn(new String(Hex.encodeHex(sessionId)));

    String remoteAddress = "1.2.3.4";
    EasyMock.expect(mockServletRequest.getRemoteAddr()).andReturn(remoteAddress);

    // prepare
    EasyMock.replay(mockServletRequest, mockServletConfig);

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);

    try {
        this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession);
        fail();
    } catch (SecurityException e) {
        // expected
    }

    // verify
    EasyMock.verify(mockServletRequest, mockServletConfig);
    assertFalse(AuthenticationTestService.isCalled());
    assertNull(AuditTestService.getAuditUserId());
    assertEquals(remoteAddress, AuditTestService.getAuditRemoteAddress());
    assertEquals(certificate, AuditTestService.getAuditClientCertificate());
    assertNull(testHttpSession.getAttribute("eid.identifier"));
}

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

protected static PKIMessage genRenewalReq(X500Name userDN, Certificate cacert, byte[] nonce, byte[] transid,
        KeyPair keys, boolean raVerifiedPopo, X500Name reqSubjectDN, String reqIssuerDN,
        AlgorithmIdentifier pAlg, DEROctetString senderKID) throws IOException, NoSuchAlgorithmException,
        InvalidKeyException, SignatureException, CertificateEncodingException {

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    myCertTemplate.setValidity(myOptionalValidity);

    if (reqSubjectDN != null) {
        myCertTemplate.setSubject(reqSubjectDN);
    }//  w w w .  j  av  a 2 s .c  om
    if (reqIssuerDN != null) {
        myCertTemplate.setIssuer(new X500Name(reqIssuerDN));
    }

    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (raVerifiedPopo) {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg);
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);

        DERBitString bs = new DERBitString(sig.sign());

        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    }

    // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new
    // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new
    // DERInteger(1122334455)));
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String("foo123"));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN),
            new GeneralName(new JcaX509CertificateHolder((X509Certificate) cacert).getSubject()));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(pAlg);
    myPKIHeader.setSenderKID(senderKID);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;

}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * This assumes that authentication is the last piece of info in handshake
 *///from w w w.jav a2s  .  c o m
public void writeCredentials(DataOutputStream dos, DataInputStream dis, Properties p_credentials,
        boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos)
        throws IOException, GemFireSecurityException {

    if (p_credentials == null) {
        // No credentials indicator
        heapdos.writeByte(CREDENTIALS_NONE);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return;
    }

    if (dhSKAlgo == null || dhSKAlgo.length() == 0) {
        // Normal credentials without encryption indicator
        heapdos.writeByte(CREDENTIALS_NORMAL);
        DataSerializer.writeProperties(p_credentials, heapdos);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return;
    }

    try {
        InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter();
        securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo);
        boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0);
        if (requireAuthentication) {
            securityLogWriter.fine("HandShake: server authentication using digital " + "signature required");
        }
        // Credentials with encryption indicator
        heapdos.writeByte(CREDENTIALS_DHENCRYPT);
        heapdos.writeBoolean(requireAuthentication);
        // Send the symmetric encryption algorithm name
        DataSerializer.writeString(dhSKAlgo, heapdos);
        // Send the DH public key
        byte[] keyBytes = dhPublicKey.getEncoded();
        DataSerializer.writeByteArray(keyBytes, heapdos);
        byte[] clientChallenge = null;
        if (requireAuthentication) {
            // Authentication of server should be with the client supplied
            // challenge
            clientChallenge = new byte[64];
            random.nextBytes(clientChallenge);
            DataSerializer.writeByteArray(clientChallenge, heapdos);
        }
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();

        // Expect the alias and signature in the reply
        byte acceptanceCode = dis.readByte();
        if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) {
            // Ignore the useless data
            dis.readByte();
            dis.readInt();
            if (!isNotification) {
                DataSerializer.readByteArray(dis);
            }
            readMessage(dis, dos, acceptanceCode, member);
        } else if (acceptanceCode == REPLY_OK) {
            // Get the public key of the other side
            keyBytes = DataSerializer.readByteArray(dis);
            if (requireAuthentication) {
                String subject = DataSerializer.readString(dis);
                byte[] signatureBytes = DataSerializer.readByteArray(dis);
                if (!certificateMap.containsKey(subject)) {
                    throw new AuthenticationFailedException(
                            LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0
                                    .toLocalizedString(subject));
                }

                // Check the signature with the public key
                X509Certificate cert = (X509Certificate) certificateMap.get(subject);
                Signature sig = Signature.getInstance(cert.getSigAlgName());
                sig.initVerify(cert);
                sig.update(clientChallenge);
                // Check the challenge string
                if (!sig.verify(signatureBytes)) {
                    throw new AuthenticationFailedException(
                            "Mismatch in client " + "challenge bytes. Malicious server?");
                }
                securityLogWriter
                        .fine("HandShake: Successfully verified the " + "digital signature from server");
            }

            byte[] challenge = DataSerializer.readByteArray(dis);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFact = KeyFactory.getInstance("DH");
            // PublicKey pubKey = keyFact.generatePublic(x509KeySpec);
            this.clientPublicKey = keyFact.generatePublic(x509KeySpec);

            HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT);
            try {
                DataSerializer.writeProperties(p_credentials, hdos);
                // Also add the challenge string
                DataSerializer.writeByteArray(challenge, hdos);

                // byte[] encBytes = encrypt.doFinal(hdos.toByteArray());
                byte[] encBytes = encryptBytes(hdos.toByteArray(),
                        getEncryptCipher(dhSKAlgo, this.clientPublicKey));
                DataSerializer.writeByteArray(encBytes, dos);
            } finally {
                hdos.close();
            }
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex);
    }
    dos.flush();
}

From source file:org.structr.util.StructrLicenseManager.java

private boolean verify(final byte[] data, final byte[] signatureData) {

    try {/*from  w  w  w  .j  a v  a 2  s. c om*/

        final Signature verifier = Signature.getInstance(SignatureAlgorithm);

        verifier.initVerify(certificate);
        verifier.update(data);

        if (verifier.verify(signatureData)) {

            return true;
        }

    } catch (Throwable t) {
        logger.warn("Unable to verify volume license: {}", t.getMessage());
    }

    logger.error("License verification failed, license is not valid.");

    return false;
}

From source file:cl.nic.dte.util.XMLUtil.java

public static AUTORIZACIONDocument generateAuthorization(AUTORIZACIONDocument template, PrivateKey pKey)
        throws NoSuchAlgorithmException, SignatureException, TransformerException, InvalidKeyException,
        IOException {/*  w w  w .j a va 2s.  com*/
    // Generation of keys

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);
    KeyPair kp = kpg.generateKeyPair();

    CAFType caf = template.getAUTORIZACION().getCAF();
    CAFType.DA.RSAPK rsapk = caf.getDA().addNewRSAPK();

    rsapk.setM(((RSAPublicKey) kp.getPublic()).getModulus().toByteArray());
    rsapk.setE(((RSAPublicKey) kp.getPublic()).getPublicExponent().toByteArray());

    ResourceBundle labels = ResourceBundle.getBundle("cl.nic.dte.resources.VerifyResults");

    Signature sig = null;
    if (pKey.getAlgorithm().equals("RSA")) {
        sig = Signature.getInstance("SHA1withRSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withRSA");
    } else if (pKey.getAlgorithm().equals("DSA")) {
        sig = Signature.getInstance("SHA1withDSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withDSA");
    } else {
        throw new NoSuchAlgorithmException(
                labels.getString("ALGORITHM_NOT_SUPPORTED").replaceAll("%1", pKey.getAlgorithm()));
    }

    template.getAUTORIZACION()
            .setRSASK("-----BEGIN RSA PRIVATE KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPrivate().getEncoded(), true))
                    + "-----END RSA PRIVATE KEY-----\n");

    template.getAUTORIZACION()
            .setRSAPUBK("-----BEGIN RSA PUBLIC KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPublic().getEncoded(), true))
                    + "-----END RSA PUBLIC KEY-----\n");

    sig.initSign(pKey);
    sig.update(XMLUtil.getCleaned(caf.getDA()));

    caf.getFRMA().setByteArrayValue(Base64.encodeBase64(sig.sign()));
    return template;
}

From source file:org.dasein.cloud.google.GoogleMethod.java

static @Nonnull String getToken(@Nonnull String iss, @Nonnull String p12File) throws CloudException {
    if (logger.isDebugEnabled()) {
        logger.debug("iss: " + iss);
        logger.debug("p12File: " + p12File);
    }//ww  w. j  av a 2  s  .c om

    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    StringBuffer token = new StringBuffer();

    try {
        token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8")));

        token.append(".");

        String scope = "https://www.googleapis.com/auth/compute";
        String aud = "https://accounts.google.com/o/oauth2/token";
        String expiry = Long.toString((System.currentTimeMillis() / 1000) + 3600);
        String startTime = Long.toString((System.currentTimeMillis() / 1000));

        String payload = "{\"iss\": \"" + iss + "\", \"scope\": \"" + scope + "\", \"aud\": \"" + aud
                + "\", \"exp\": \"" + expiry + "\", \"iat\": \"" + startTime + "\"}";

        token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8")));

        // TODO: the password is hardcoded. This has to be read from the ctx or from the environment variable
        char[] password = "notasecret".toCharArray();
        FileInputStream iStream = new FileInputStream(new File(p12File));
        KeyStore store = KeyStore.getInstance("PKCS12");
        try {
            store.load(iStream, password);
        } finally {
            try {
                iStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("Could not read the keystore file");
                throw new CloudException(e);
            }
        }
        String alias = "";

        Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            String keyStoreAlias = aliases.nextElement().toString();
            if (store.isKeyEntry(keyStoreAlias)) {
                alias = keyStoreAlias;
                break;
            }
        }

        PrivateKey privateKey = (PrivateKey) store.getKey(alias, password);

        Signature shaSignature = Signature.getInstance("SHA256withRSA");
        shaSignature.initSign(privateKey);
        shaSignature.update(token.toString().getBytes("UTF-8"));
        String signedToken = Base64.encodeBase64URLSafeString(shaSignature.sign());

        //Separate with a period
        token.append(".");

        //Add the encoded signature
        token.append(signedToken);
        return token.toString();

    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Could not sign the payload with the private key");
        throw new CloudException(e);
    }
}