List of usage examples for java.security Signature getInstance
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java
@Test public void testHandleMessageExpiredChallenge() throws Exception { // setup// ww w . ja v a 2 s.c o m 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); byte[] challenge = AuthenticationChallenge.generateChallenge(testHttpSession); Thread.sleep(1000); // > 1 ms AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId, null, challenge); 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("1"); // 1 ms 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(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(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(mockServletRequest.getRemoteAddr()).andStubReturn("remote-address"); EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session")) .andStubReturn(new String(Hex.encodeHex(sessionId))); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME)) .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); // 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 (ServletException e) { // verify EasyMock.verify(mockServletRequest, mockServletConfig); assertNull(AuditTestService.getAuditUserId()); assertNull(testHttpSession.getAttribute("eid.identifier")); assertEquals(certificate, AuditTestService.getAuditClientCertificate()); assertEquals("remote-address", AuditTestService.getAuditRemoteAddress()); } }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testPSS256() throws Exception { Security.addProvider(new BeIDProvider()); Security.addProvider(new BouncyCastleProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);//w w w.ja v a 2 s . c om PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); PublicKey authnPublicKey = authnCertificate.getPublicKey(); Signature signature = Signature.getInstance("SHA256withRSAandMGF1"); 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); }
From source file:com.axelor.apps.account.service.payment.PayboxService.java
/** * verification signature RSA des donnees avec cle publique * @param dataBytes//w w w . jav a 2 s . c o m * @param sigBytes * @param pubKey * @return * @throws Exception */ private boolean verify(byte[] dataBytes, byte[] sigBytes, String sigAlg, PublicKey pubKey) throws Exception { Signature signature = Signature.getInstance(sigAlg); signature.initVerify(pubKey); signature.update(dataBytes); return signature.verify(sigBytes); }
From source file:org.wso2.carbon.appmgt.impl.token.JWTGenerator.java
/** * Helper method to sign the JWT/*from w ww. ja v a 2s.co m*/ * * @param assertion * @param endUserName * @return signed assertion * @throws org.wso2.carbon.appmgt.api.AppManagementException */ private byte[] signJWT(String assertion, String endUserName) throws AppManagementException { try { //get tenant domain String tenantDomain = MultitenantUtils.getTenantDomain(endUserName); //get tenantId int tenantId = getTenantId(endUserName); Key privateKey = null; if (!(privateKeys.containsKey(tenantId))) { AppManagerUtil.loadTenantRegistry(tenantId); //get tenant's key store manager KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { //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(); signature.update(dataInBytes); //sign the assertion and return the signature byte[] signedInfo = signature.sign(); return signedInfo; } catch (NoSuchAlgorithmException e) { String error = "Signature algorithm not found."; //do not log throw new AppManagementException(error); } catch (InvalidKeyException e) { String error = "Invalid private key provided for the signature"; //do not log throw new AppManagementException(error); } catch (SignatureException e) { String error = "Error in signature"; //do not log throw new AppManagementException(error); } catch (AppManagementException e) { //do not log throw new AppManagementException(e.getMessage()); } }
From source file:biz.bokhorst.xprivacy.Util.java
private static boolean verifyData(byte[] data, byte[] signature, PublicKey publicKey) throws Throwable { // Verify signature Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(publicKey);//from w ww .j ava2s . c o m verifier.update(data); return verifier.verify(signature); }
From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java
public void validateQueryString(RoleDescriptorType md, String queryString) throws SamlR2SignatureException, SamlR2SignatureValidationException { try {/*from w w w . j a v a 2 s . c om*/ X509Certificate cert = getX509Certificate(md); if (cert == null) { logger.error("No Certificate found in Metadata " + md.getID()); throw new SamlR2SignatureException("No Certificate found in Metadata " + md.getID()); } if (queryString == null || queryString.length() == 0) { logger.error("SAML 2.0 Qery string null"); throw new SamlR2SignatureException("SAML 2.0 Qery string null"); } if (logger.isTraceEnabled()) logger.trace("SAML 2.0 Query string to validate [" + queryString + "]"); StringTokenizer st = new StringTokenizer(queryString, "&"); String samlParam; String samlRequest = null; String samlResponse = null; String relayState = null; String sigAlg = null; String encSig = null; while (st.hasMoreTokens()) { samlParam = st.nextToken(); if (samlParam.startsWith("SAMLRequest")) { samlRequest = samlParam; } else if (samlParam.startsWith("SAMLResponse")) { samlResponse = samlParam; } else if (samlParam.startsWith("RelayState")) { relayState = samlParam; } else if (samlParam.startsWith("SigAlg")) { sigAlg = samlParam; } else if (samlParam.startsWith("Signature")) { encSig = samlParam; } else { // Ignore this token ... logger.warn("Non-SAML 2.0 parameter ignored " + samlParam); } } if ((samlRequest == null || samlRequest.equals("")) && (samlResponse == null || samlResponse.equals(""))) throw new SamlR2SignatureValidationException( "SAML 2.0 Query string MUST contain either 'SAMLRequest' or 'SAMLResponse' parameter"); if (sigAlg == null || sigAlg.equals("")) throw new SamlR2SignatureValidationException( "SAML 2.0 Query string MUST contain a 'SigAlg' parameter"); if (encSig == null || encSig.equals("")) { throw new SamlR2SignatureValidationException( "SAML 2.0 Query string MUST contain a 'Signature' parameter"); } // Re-order paramters just in case they were mixed-up while getting here. String newQueryString = null; if (samlRequest != null) { newQueryString = samlRequest; } else { newQueryString = samlResponse; } if (relayState != null) { newQueryString += "&" + relayState; } newQueryString += "&" + sigAlg; if (logger.isDebugEnabled()) logger.debug( "SAML 2.0 Query string signature validation for (re-arranged) [" + newQueryString + "]"); int sigAlgValueIndex = sigAlg.indexOf('='); // Get Signature Algorithm String sigAlgValue = sigAlg.substring(sigAlgValueIndex + 1); if (sigAlgValue == null || sigAlgValue.equals("")) { throw new SamlR2SignatureValidationException( "SAML 2.0 Query string MUST contain a 'SigAlg' parameter value"); } sigAlgValue = URLDecoder.decode(sigAlgValue, "UTF-8"); if (logger.isTraceEnabled()) logger.trace("SigAlg=" + sigAlgValue); // Get Signature value int encSigValueIndex = encSig.indexOf('='); String signatureEnc = encSig.substring(encSigValueIndex + 1); if (signatureEnc == null || signatureEnc.equals("")) { throw new SamlR2SignatureValidationException( "SAML 2.0 Query string MUST contain a 'Signature' parameter value"); } signatureEnc = URLDecoder.decode(signatureEnc, "UTF-8"); if (logger.isTraceEnabled()) logger.trace("Signature=" + signatureEnc); // base-64 decode the signature value byte[] signatureBin = null; Base64 decoder = new Base64(); signatureBin = decoder.decode(signatureEnc.getBytes()); // get Signature instance based on algorithm // TODO : Support SHA-256 Signature signature = null; if (sigAlgValue.equals(SignatureMethod.DSA_SHA1)) { signature = Signature.getInstance(SHA1_WITH_DSA); } else if (sigAlgValue.equals(SignatureMethod.RSA_SHA1)) { signature = Signature.getInstance(SHA1_WITH_RSA); } else { throw new SamlR2SignatureException("SAML 2.0 Siganture does not support algorithm " + sigAlgValue); } // now verify signature signature.initVerify(cert); signature.update(newQueryString.getBytes()); if (!signature.verify(signatureBin)) { // TODO : Get information about the error ?! throw new SamlR2SignatureValidationException("Invalid digital signature"); } if (!validateCertificate(md, null)) { throw new SamlR2SignatureValidationException("Certificate is not valid, check logs for details"); } } catch (Exception e) { logger.error("Cannot verify digital SAML 2.0 Query string signature " + e.getMessage(), e); throw new SamlR2SignatureException( "Cannot verify digital SAML 2.0 Query string signature " + e.getMessage(), e); } }
From source file:org.structr.util.StructrLicenseManager.java
private static void sign(final Map<String, String> properties, final String keystoreFileName, final String password) { final String src = collectLicenseFieldsForSignature(properties); try {/*from w ww. j a va 2s .co m*/ final byte[] data = src.getBytes(CharSet); final Signature signer = Signature.getInstance(SignatureAlgorithm); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (final InputStream is = new FileInputStream(keystoreFileName)) { keyStore.load(is, password.toCharArray()); final Key key = keyStore.getKey(KeystoreAlias, password.toCharArray()); signer.initSign((PrivateKey) key); signer.update(data); properties.put(SignatureKey, Hex.encodeHexString(signer.sign())); } } catch (Throwable t) { logger.warn("Unable to sign license.", t); } }
From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java
@Override public String signMessage(String message) throws IllegalStateException { Validate.notNull(this.getSignAlgorithm()); Validate.notNull(this.getPrivateKey()); try {// ww w . j a v a 2 s .c o m Signature sig = Signature.getInstance(this.getSignAlgorithm().getAlgorithmName()); sig.initSign(privateKey); byte[] messageBytes = message.getBytes("UTF-8"); sig.update(messageBytes); byte[] sigBytes = sig.sign(); String signature = Shared.encodeBytes(sigBytes); if (signature == null || signature.isEmpty()) { log.debug("Invalid signature - either null or empty. "); } return signature; } catch (Exception e) { log.error("Caught exception while signing message " + message + ", sigAlg " + this.getSignAlgorithm().getAlgorithmName()); throw new IllegalStateException(e); } }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
private void verifySignatureAlgorithm(final String signatureAlgorithm, final PrivateKey privateKey, final PublicKey publicKey) throws Exception { Signature signature = Signature.getInstance(signatureAlgorithm); signature.initSign(privateKey);/* w w w. j a va2s . co m*/ assertTrue(signature.getProvider() instanceof BeIDProvider); final byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); final byte[] signatureValue = signature.sign(); assertNotNull(signatureValue); signature.initVerify(publicKey); signature.update(toBeSigned); final boolean beIDResult = signature.verify(signatureValue); assertTrue(beIDResult); signature = Signature.getInstance(signatureAlgorithm); signature.initVerify(publicKey); signature.update(toBeSigned); final boolean result = signature.verify(signatureValue); assertTrue(result); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; BigInteger signatureValueBigInteger = new BigInteger(signatureValue); BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); LOG.debug("Padded DigestInfo: " + new String(Hex.encodeHex(messageBigInteger.toByteArray()))); }
From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java
/** * Verifies that the supplied private key and signed certificate match by signing/verifying some test data. * /*from w w w. j a va 2 s.c o m*/ * @param privateKey A private key * @param cert the certificate * @throws ResourceException if the verification fails, or an error is encountered. */ protected void verify(PrivateKey privateKey, Certificate cert) throws ResourceException { PublicKey publicKey = cert.getPublicKey(); byte[] data = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 }; boolean verified; try { Signature signer = Signature.getInstance(privateKey.getAlgorithm()); signer.initSign(privateKey); signer.update(data); byte[] signed = signer.sign(); Signature verifier = Signature.getInstance(publicKey.getAlgorithm()); verifier.initVerify(publicKey); verifier.update(data); verified = verifier.verify(signed); } catch (Exception e) { throw new InternalServerErrorException("Error verifying private key and signed certificate", e); } if (!verified) { throw new BadRequestException("Private key does not match signed certificate"); } }