Example usage for java.security Signature initSign

List of usage examples for java.security Signature initSign

Introduction

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

Prototype

public final void initSign(PrivateKey privateKey) throws InvalidKeyException 

Source Link

Document

Initialize this object for signing.

Usage

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testNonRepudiationSignature() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);/*from   ww  w .  jav  a  2  s. c  o m*/
    PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(signPrivateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    assertNotNull(signatureValue);

    Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature");
    assertNotNull(signCertificateChain);
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testNonRepudiationSignaturePPDU() throws Exception {

    CCID.riskPPDU(true);/*from  w w w.j av a2  s .c  o  m*/

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(signPrivateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    assertNotNull(signatureValue);

    Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature");
    assertNotNull(signCertificateChain);
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testLocale() throws Exception {
    Security.addProvider(new BeIDProvider());

    KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter beIDKeyStoreParameter = new BeIDKeyStoreParameter();
    beIDKeyStoreParameter.setLocale(Locale.FRENCH);
    beIDKeyStoreParameter.setLogger(new TestLogger());
    keyStore.load(beIDKeyStoreParameter);

    PrivateKey privateKey = (PrivateKey) keyStore.getKey("Signature", null);

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);/*w w w. ja  v  a 2  s .co m*/
    signature.sign();
}

From source file:org.wso2.carbon.apimgt.keymgt.token.AbstractJWTGenerator.java

private byte[] signJWT(String assertion, String endUserName) throws APIManagementException {

    String tenantDomain = null;/*from  w  w w.jav  a 2s. c o m*/

    try {
        //get tenant domain
        tenantDomain = MultitenantUtils.getTenantDomain(endUserName);
        //get tenantId
        int tenantId = APIUtil.getTenantId(endUserName);

        Key privateKey = null;

        if (!(privateKeys.containsKey(tenantId))) {
            APIUtil.loadTenantRegistry(tenantId);
            //get tenant's key store manager
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                //derive key store name
                String ksName = tenantDomain.trim().replace('.', '-');
                String jksName = ksName + ".jks";
                //obtain private key
                //TODO: maintain a hash map with tenants' private keys after first initialization
                privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain);
            } else {
                try {
                    privateKey = tenantKSM.getDefaultPrivateKey();
                } catch (Exception e) {
                    log.error("Error while obtaining private key for super tenant", e);
                }
            }
            if (privateKey != null) {
                privateKeys.put(tenantId, privateKey);
            }
        } else {
            privateKey = privateKeys.get(tenantId);
        }

        //initialize signature with private key and algorithm
        Signature signature = Signature.getInstance(signatureAlgorithm);
        signature.initSign((PrivateKey) privateKey);

        //update signature with data to be signed
        byte[] dataInBytes = assertion.getBytes(Charset.defaultCharset());
        signature.update(dataInBytes);

        //sign the assertion and return the signature
        return signature.sign();

    } catch (NoSuchAlgorithmException e) {
        String error = "Signature algorithm not found.";
        //do not log
        throw new APIManagementException(error, e);
    } catch (InvalidKeyException e) {
        String error = "Invalid private key provided for the signature";
        //do not log
        throw new APIManagementException(error, e);
    } catch (SignatureException e) {
        String error = "Error in signature";
        //do not log
        throw new APIManagementException(error, e);
    } catch (RegistryException e) {
        String error = "Error in loading tenant registry for " + tenantDomain;
        //do not log
        throw new APIManagementException(error, e);
    }
}

From source file:org.wso2.carbon.appmgt.gateway.token.AbstractJWTGenerator.java

/**
 * Helper method to sign the JWT//from  w  w w .j a va  2  s  . c  o  m
 *
 * @param assertion Assertion
 * @param endUserName End user name
 * @return signed assertion
 * @throws AppManagementException on error while trying to sign JWT
 */
private byte[] signJWT(String assertion, String endUserName) throws AppManagementException {
    int tenantId = getTenantId(endUserName);
    try {
        Key privateKey = getPrivateKey(endUserName, tenantId);
        if (privateKey == null) {
            throw new AppManagementException("Private key is null for tenant " + tenantId);
        }
        /* Initialize signature with private key and algorithm */
        Signature signature = Signature.getInstance(signatureAlgorithm);
        signature.initSign((PrivateKey) privateKey);

        /* Update signature with data to be signed */
        byte[] dataInBytes = assertion.getBytes(StandardCharsets.UTF_8);
        signature.update(dataInBytes);

        /* Sign the assertion and return the signature */
        byte[] signedInfo = signature.sign();
        return signedInfo;
    } catch (NoSuchAlgorithmException e) {
        String error = "Signature algorithm " + signatureAlgorithm + " not found.";
        log.error(error, e);
        throw new AppManagementException(error, e);
    } catch (InvalidKeyException e) {
        String error = "Invalid private key provided for the signature for tenant " + tenantId;
        log.error(error, e);
        throw new AppManagementException(error, e);
    } catch (SignatureException e) {
        String error = "Error in signature algorithm " + signatureAlgorithm;
        log.error(error, e);
        throw new AppManagementException(error, e);
    } catch (AppManagementException e) {
        String error = "Error in obtaining tenant's " + tenantId + " private key";
        log.error(error, e);
        throw new AppManagementException(error, e);
    }
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testSwingParent2() throws Exception {
    Security.addProvider(new BeIDProvider());

    MyFrame myFrame = new MyFrame();

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(myFrame);//from   w  w  w  . j  a va  2s  .  c o  m

    final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    Certificate[] certificateChain = keyStore.getCertificateChain("Authentication");
    signature.initVerify(certificateChain[0]);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java

private byte[] createSignature(PrivateKey privateKey) throws SpkacException {
    try {/*from  w  ww. ja v  a2s  .  c o m*/
        byte[] publicKeyAndChallenge = createPublicKeyAndChallengeForSigning();

        Signature sig = Signature.getInstance(getSignatureAlgorithm().jce());
        sig.initSign(privateKey);
        sig.update(publicKeyAndChallenge);

        return sig.sign();
    } catch (GeneralSecurityException ex) {
        throw new SpkacException(res.getString("NoCreateSpkacSignature.exception.message"), ex);
    }
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testRecoveryAfterRemoval() throws Exception {
    Security.addProvider(new BeIDProvider());

    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//from w  w  w. ja  va2  s. com

    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    signature.sign();

    JOptionPane.showMessageDialog(null, "Please remove/insert eID card...");

    keyStore.load(null); // reload the keystore.
    authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    signature.initSign(authnPrivateKey);
    signature.update(toBeSigned);
    signature.sign();
}

From source file:com.tremolosecurity.proxy.auth.saml2.Saml2SingleLogout.java

@Override
public void handleLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    if (request == null || response == null) {
        //do nothing
        return;//from ww  w  . j av  a2 s. c  o  m
    }

    String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(digSigAlg);

    if (xmlAlg == null) {
        throw new ServletException("Unknown Signiture algorithm : '" + digSigAlg + "'");
    }

    String javaAlg = SAML2Auth.javaDigSigAlgs.get(digSigAlg);

    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);

    ConfigManager cfgMgr = holder.getConfig();

    LogoutRequestBuilder lrb = new LogoutRequestBuilder();
    LogoutRequest lr = lrb.buildObject();

    DateTime dt = new DateTime();
    lr.setIssueInstant(dt);

    lr.setDestination(logoutURL);

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);

    String id = "f" + Hex.encodeHexString(idBytes);
    lr.setID(id);

    IssuerBuilder ib = new IssuerBuilder();
    Issuer issuer = ib.buildObject();
    issuer.setValue(assertionConsumerServiceURL);
    lr.setIssuer(issuer);

    NameIDBuilder nidbpb = new NameIDBuilder();
    NameID nid = nidbpb.buildObject();
    //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
    nid.setFormat(nameIDFormat);

    //nid.setSPNameQualifier(assertionConsumerServiceURL);
    nid.setValue(nameID);
    lr.setNameID(nid);

    SessionIndexBuilder sib = new SessionIndexBuilder();
    SessionIndex si = sib.buildObject();
    si.setSessionIndex(sessionIndex);
    lr.getSessionIndexes().add(si);

    try {
        // Get the Subject marshaller
        Marshaller marshaller = new LogoutRequestMarshaller();

        // Marshall the Subject
        //Element assertionElement = marshaller.marshall(lr);

        String xml = OpenSAMLUtils.xml2str(lr);
        xml = xml.substring(xml.indexOf("?>") + 2);

        if (logger.isDebugEnabled()) {
            logger.debug("=======AuthnRequest============");
            logger.debug(xml);
            logger.debug("=======AuthnRequest============");
        }

        byte[] bxml = xml.getBytes("UTF-8");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
                new Deflater(Deflater.BEST_COMPRESSION, true));

        compressor.write(bxml);
        compressor.flush();
        compressor.close();

        String b64 = new String(Base64.encodeBase64(baos.toByteArray()));
        StringBuffer redirURL = new StringBuffer();
        StringBuffer query = new StringBuffer();

        idBytes = new byte[20];
        random.nextBytes(idBytes);

        query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=")
                .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8"));

        query.append("&SigAlg=").append(URLEncoder.encode(xmlAlg, "UTF-8"));
        //http://www.w3.org/2000/09/xmldsig#rsa-sha1

        java.security.Signature signer = java.security.Signature.getInstance(javaAlg);

        PrivateKey sigKey = cfgMgr.getPrivateKey(signingKeyAlias);

        if (sigKey == null) {
            throw new ServletException("Signing Key : '" + signingKeyAlias + "' not found");
        }

        signer.initSign(sigKey);
        signer.update(query.toString().getBytes("UTF-8"));
        String base64Sig = new String(Base64.encodeBase64(signer.sign()));
        query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8"));

        redirURL.append(logoutURL).append("?").append(query.toString());

        if (logger.isDebugEnabled()) {
            logger.debug("Logout URL : '" + redirURL.toString() + "'");
        }

        //((ProxyResponse) response).removeHeader("Location");
        response.sendRedirect(redirURL.toString());

    } catch (Exception e) {
        throw new ServletException("Could not generate logout request", e);
    }

}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testSwingParentLocale() throws Exception {
    Security.addProvider(new BeIDProvider());

    final JFrame frame = new JFrame("Test Parent frame");
    frame.setSize(200, 200);/*from  www . j ava2 s  .c  om*/
    frame.setLocation(300, 300);
    frame.setVisible(true);

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    final BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    keyStoreParameter.setLogoff(true);
    keyStoreParameter.setParentComponent(frame);
    keyStoreParameter.setLocale(new Locale("nl"));
    keyStore.load(keyStoreParameter);

    final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    signature.sign();
}