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:org.springframework.boot.actuate.autoconfigure.cloudfoundry.reactive.ReactiveTokenValidatorTests.java

private String getSignedToken(byte[] header, byte[] claims) throws Exception {
    PrivateKey privateKey = getPrivateKey();
    Signature signature = Signature.getInstance("SHA256WithRSA");
    signature.initSign(privateKey);//from  w  ww.  java  2s  .c  o  m
    byte[] content = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encode(claims));
    signature.update(content);
    byte[] crypto = signature.sign();
    byte[] token = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encodeUrlSafe(claims),
            Base64Utils.encodeUrlSafe(crypto));
    return new String(token, StandardCharsets.UTF_8);
}

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

@Test
public void testHandleMessageInvalidSignature() throws Exception {
    // setup//from www.j  ava 2  s.  c  o m
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore,
            notAfter, null, keyPair.getPrivate(), true, 0, null, null);

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

    EasyMock.expect(mockServletConfig.getInitParameter("AuditService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass"))
            .andStubReturn(AuditTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("SignatureService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("SignatureServiceClass"))
            .andStubReturn(SignatureTestService.class.getName());

    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("remote-address");

    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    byte[] document = "hello world".getBytes();
    byte[] digestValue = messageDigest.digest(document);
    EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_VALUE_SESSION_ATTRIBUTE))
            .andStubReturn(digestValue);
    EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_ALGO_SESSION_ATTRIBUTE))
            .andStubReturn("SHA-1");

    SignatureDataMessage message = new SignatureDataMessage();
    message.certificateChain = new LinkedList<X509Certificate>();
    message.certificateChain.add(certificate);

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(keyPair.getPrivate());
    signature.update("foobar-document".getBytes());
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

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

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);
    try {
        this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession);
        fail();
    } catch (ServletException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // verify
        EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest);
        assertNull(SignatureTestService.getSignatureValue());
        assertEquals("remote-address", AuditTestService.getAuditSignatureRemoteAddress());
        assertEquals(certificate, AuditTestService.getAuditSignatureClientCertificate());
    }
}

From source file:com.tremolosecurity.idp.providers.Saml2Idp.java

private void procAuthnReq(HttpServletRequest request, HttpServletResponse response,
        DocumentBuilderFactory factory, String saml, String relayState) throws ParserConfigurationException,
        SAXException, IOException, UnmarshallingException, Exception, UnsupportedEncodingException,
        NoSuchAlgorithmException, InvalidKeyException, SignatureException, ServletException {
    AuthnRequestUnmarshaller marshaller = new AuthnRequestUnmarshaller();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Element root = builder.parse(new InputSource(new StringReader(saml))).getDocumentElement();

    AuthnRequest authn = (AuthnRequest) marshaller.unmarshall(root);

    String issuer = authn.getIssuer().getValue();

    String authnCtx = null;/*from ww w. j av  a2s.  co  m*/

    if (authn.getRequestedAuthnContext() == null
            || authn.getRequestedAuthnContext().getAuthnContextClassRefs().size() == 0
            || authn.getRequestedAuthnContext().getAuthnContextClassRefs().get(0)
                    .getAuthnContextClassRef() == null) {
        //no authnCtx information, use default
        authnCtx = null;
    } else {
        authnCtx = authn.getRequestedAuthnContext().getAuthnContextClassRefs().get(0).getAuthnContextClassRef();
    }

    String nameID = null;

    if (authn.getNameIDPolicy() == null) {
        nameID = null;
    } else {
        nameID = authn.getNameIDPolicy().getFormat();
    }

    String binding = authn.getProtocolBinding();
    String url = authn.getAssertionConsumerServiceURL();

    if (logger.isDebugEnabled()) {
        logger.debug("Issuer : '" + issuer + "'");
        logger.debug("Binding : '" + binding + "'");
        logger.debug("URL : '" + url + "'");

        logger.debug("NameID Format : '" + nameID + "'");
        logger.debug("Authn Class Ctx : '" + authnCtx + "'");
    }

    Saml2Trust trust = this.trusts.get(issuer);

    if (trust == null) {
        StringBuffer b = new StringBuffer();
        b.append("Could not find a trust for issuer '").append(issuer).append("'");
        throw new Exception(b.toString());
    }

    String authnSig = request.getParameter("Signature");
    if (authnSig != null) {
        String sigAlg = request.getParameter("SigAlg");
        StringBuffer query = new StringBuffer();
        query.append("SAMLRequest=").append(URLEncoder.encode(request.getParameter("SAMLRequest"), "UTF-8"));
        if (relayState != null) {
            query.append("&RelayState=").append(URLEncoder.encode(relayState, "UTF-8"));
        }
        query.append("&SigAlg=").append(URLEncoder.encode(sigAlg, "UTF-8"));

        String validationCert = trust.spSigCert;
        UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
        java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(validationCert);

        if (!Saml2Idp.xmlDigSigAlgs.containsKey(sigAlg)) {
            throw new Exception("Invalid signature algorithm : " + sigAlg);
        }

        if (!authn.getDestination().equals(request.getRequestURL().toString())) {
            throw new Exception("Invalid destination");
        }

        Signature sigv = Signature.getInstance(Saml2Idp.javaDigSigAlgs.get(sigAlg));

        sigv.initVerify(cert.getPublicKey());
        sigv.update(query.toString().getBytes("UTF-8"));

        if (!sigv.verify(Base64.decodeBase64(authnSig.getBytes("UTF-8")))) {
            throw new Exception("Signature verification failed");
        }

    } else if (this.requireSignedAuthn) {
        throw new Exception("No signature on the authentication request");
    }

    doFederation(request, response, issuer, nameID, authnCtx, url, relayState, trust);
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * {@code getDataValidity} is used to verify the digital signature of the
 * received data. If the verification is true then {@code true} is returned
 * otherwise {@code false}.//from  ww  w .  j  ava  2s  .  co m
 * 
 * @param key
 *            the PublicKey received from server.
 * @param data
 *            the data received from server.
 * @param serverDataSig
 *            the Signature corresponding to the received data.
 * @return Boolean value.
 * @throws NoSuchAlgorithmException
 *             if the specified algorithm is not available.
 * @throws InvalidKeyException
 *             if publicKey is not valid.
 * @throws SignatureException
 *             if this Signature instance is not initialized properly.
 */
private Boolean getDataValidity(PublicKey key, String data, String serverDataSig)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature s = Signature.getInstance("SHA256withRSA");
    s.initVerify(key);
    byte[] byte_dataFromServer = data.getBytes();
    s.update(byte_dataFromServer);
    byte[] byte_serverDataSig = Base64.decode(serverDataSig, Base64.DEFAULT);
    Boolean valid = s.verify(byte_serverDataSig);
    return valid;
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private Boolean isValidSignature(String tokenString, byte[] signature) {

    Boolean isValid = false;/*  w w w  . j ava  2s .c  om*/

    File lterCert = ConfigurationListener.getLterCertificate();

    try {

        FileInputStream certFis = new FileInputStream(lterCert);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(certFis);

        PublicKey pubKey = cert.getPublicKey();

        Signature sig = Signature.getInstance("MD5withRSA");
        sig.initVerify(pubKey);

        sig.update(tokenString.getBytes());
        isValid = sig.verify(signature);

    } catch (FileNotFoundException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (CertificateException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (SignatureException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    }

    return isValid;

}

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

/**
 * Verify SPKAC./*from w  w  w  . j a  va 2s  .  com*/
 *
 * @return True if verified successfully, false otherwise
 * @throws SpkacException
 *             If verification fails
 */
public boolean verify() throws SpkacException {
    try {
        byte[] publicKeyAndChallenge = createPublicKeyAndChallengeForSigning();

        Signature sig = Signature.getInstance(getSignatureAlgorithm().jce());
        sig.initVerify(getPublicKey());
        sig.update(publicKeyAndChallenge);

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

    }
}

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

@Test
public void testPSSPrefix() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);/*from  w w  w .j  a  v  a2 s. c  om*/
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA1withRSAandMGF1");
    signature.initSign(authnPrivateKey);

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

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    RSAPublicKey rsaPublicKey = (RSAPublicKey) authnPublicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    String paddedMessage = new String(Hex.encodeHex(messageBigInteger.toByteArray()));
    LOG.debug("padded message: " + paddedMessage);
    assertTrue(paddedMessage.endsWith("bc"));
}

From source file:test.be.fedict.eid.applet.SecurePinPadReaderTest.java

/**
 * When creating a non-repudiation signature using PKCS#1-SHA1 (non-naked)
 * the digest value should also be confirmed via the secure pinpad reader.
 * /*from   w  w  w.  j  av  a2 s. co m*/
 * @throws Exception
 */
@Test
@QualityAssurance(firmware = Firmware.V015Z, approved = true)
public void testNonRepSignPKCS1_SHA1() throws Exception {
    CardChannel cardChannel = this.pcscEid.getCardChannel();

    List<X509Certificate> signCertChain = this.pcscEid.getSignCertificateChain();

    CommandAPDU setApdu = new CommandAPDU(0x00, 0x22, 0x41, 0xB6, new byte[] { 0x04, // length of following data
            (byte) 0x80, // algo ref
            0x02, // RSA PKCS#1 SHA1
            (byte) 0x84, // tag for private key ref
            (byte) 0x83 }); // non-rep key
    ResponseAPDU responseApdu = cardChannel.transmit(setApdu);
    assertEquals(0x9000, responseApdu.getSW());

    this.pcscEid.verifyPin();

    byte[] data = "My Testcase".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    byte[] digestValue = messageDigest.digest(data);

    CommandAPDU computeDigitalSignatureApdu = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, digestValue);

    responseApdu = cardChannel.transmit(computeDigitalSignatureApdu);
    assertEquals(0x9000, responseApdu.getSW());
    byte[] signatureValue = responseApdu.getData();
    LOG.debug("signature value size: " + signatureValue.length);

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(signCertChain.get(0).getPublicKey());
    signature.update(data);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:be.fedict.eid.applet.service.impl.handler.IdentityDataMessageHandler.java

private void verifySignature(String signAlgo, byte[] signatureData, PublicKey publicKey,
        HttpServletRequest request, byte[]... data) throws ServletException {
    Signature signature;//from w  w w  . java2 s.c o m
    try {
        signature = Signature.getInstance(signAlgo);
    } catch (NoSuchAlgorithmException e) {
        throw new ServletException("algo error: " + e.getMessage(), e);
    }
    try {
        signature.initVerify(publicKey);
    } catch (InvalidKeyException e) {
        throw new ServletException("key error: " + e.getMessage(), e);
    }
    try {
        for (byte[] dataItem : data) {
            signature.update(dataItem);
        }
        boolean result = signature.verify(signatureData);
        if (false == result) {
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.identityIntegrityError(remoteAddress);
            }
            throw new ServletException("signature incorrect");
        }
    } catch (SignatureException e) {
        AuditService auditService = this.auditServiceLocator.locateService();
        if (null != auditService) {
            String remoteAddress = request.getRemoteAddr();
            auditService.identityIntegrityError(remoteAddress);
        }
        throw new ServletException("signature error: " + e.getMessage(), e);
    }
}

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

private byte[] createSignature(PrivateKey privateKey) throws SpkacException {
    try {// w w w. j  a  va 2  s. co 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);
    }
}