List of usage examples for java.security Signature update
public final void update(ByteBuffer data) throws SignatureException
From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java
/** * Verifies a signature.//from w w w . j ava 2s .c o m * * @param signatureAlgo * @param signatureData * @param publicKey * @param data * @return * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws SignatureException */ public boolean verifySignature(final String signatureAlgo, final byte[] signatureData, final PublicKey publicKey, final byte[]... data) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { Signature signature; signature = Signature.getInstance(signatureAlgo); signature.initVerify(publicKey); for (byte[] dataItem : data) { signature.update(dataItem); } final boolean result = signature.verify(signatureData); return result; }
From source file:com.santander.serenity.security.credentials.bkstoken.BKSAuthenticator.java
@Override public boolean isAuthenticated(MessageContext msgCxt) { boolean isAuthenticated = false; HttpServletRequest request = (HttpServletRequest) msgCxt.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); //Get the filesystem keystore default primary certificate KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID); BKSToken token = BKSToken.parse(request.getParameter("token")); //Validar caducidad if (System.currentTimeMillis() > token.getExpirationDate()) { log.info("BKSToken is expired"); return false; }//from w ww . j ava 2 s .co m //Valida la firma try { String publicKeyAlias = token.getEmitter() + "_" + token.getSignatureMethod(); Signature verifier = Signature.getInstance(token.getSignatureMethod()); verifier.initVerify((RSAPublicKey) keyStoreManager.getPrimaryKeyStore() .getCertificate(publicKeyAlias + ".cer").getPublicKey()); verifier.update(token.getOriginalDataWithoutSignature().getBytes()); if (!verifier.verify(Base64Utils.decode(token.getSignature()))) { return false; } } catch (Exception e) { log.error(e.getMessage()); return false; } //Valida que exista el usuario en el repo de usuarios try { String userName = token.getUserId(); String tenantDomain = MultitenantUtils.getTenantDomain(userName); userName = MultitenantUtils.getTenantAwareUsername(userName); TenantManager tenantManager = BKSAuthenticatorServiceComponent.getRealmService().getTenantManager(); int tenantId = tenantManager.getTenantId(tenantDomain); if (tenantId == -1) { log.error("tenantDomain is not valid. username : " + userName + ", tenantDomain : " + tenantDomain); return false; } handleAuthenticationStarted(tenantId); UserStoreManager userStore = ((ReadWriteLDAPUserStoreManager) BKSAuthenticatorServiceComponent .getRealmService().getTenantUserRealm(tenantId).getUserStoreManager()) .getSecondaryUserStoreManager(); if (userStore.isExistingUser(userName)) { isAuthenticated = true; } if (isAuthenticated) { CarbonAuthenticationUtil.onSuccessAdminLogin(request.getSession(), userName, tenantId, tenantDomain, "BKSTToken Authentication"); handleAuthenticationCompleted(tenantId, true); return true; } else { log.error("Authentication Request is rejected. User : " + userName + " does not exists in tenant : " + tenantDomain + " 's UserStore"); CarbonAuthenticationUtil.onFailedAdminLogin(request.getSession(), userName, tenantId, "BKSToken Authentication", "User does not exists in UserStore"); handleAuthenticationCompleted(tenantId, false); return false; } } catch (Exception e) { log.error("Error authenticating the user " + e.getMessage(), e); } return isAuthenticated; }
From source file:org.esupportail.pay.services.PayBoxService.java
public boolean checkPayboxSignature(String queryString, String signature) { String sData = queryString.substring(0, queryString.lastIndexOf("&")); try {// ww w .ja v a 2s .c o m Signature sig = Signature.getInstance("SHA1WithRSA"); byte[] sigBytes = Base64.decodeBase64(signature.getBytes()); sig.initVerify(payboxPublicKey); sig.update(sData.getBytes()); boolean signatureOk = sig.verify(sigBytes); if (!signatureOk) { log.error("Erreur lors de la vrification de la signature, les donnes ne correspondent pas."); log.error(sData); log.error(signature); } return signatureOk; } catch (Exception e) { log.warn("Pb when checking SSL signature of Paybox", e); return false; } }
From source file:com.vmware.identity.samlservice.SamlServiceTest.java
@Test public void testVerifySignature() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { // pick a sample message String message = "This is a sample message to be encoded"; // sign using our algorithm SignatureAlgorithm algo = SignatureAlgorithm.getSignatureAlgorithmForURI(TestConstants.SIGNATURE_ALGORITHM); Signature sig = Signature.getInstance(algo.getAlgorithmName()); sig.initSign(privateKey);/*from w w w.j a va 2s .co m*/ byte[] messageBytes = message.getBytes(); sig.update(messageBytes); byte[] sigBytes = sig.sign(); String signature = Shared.encodeBytes(sigBytes); // verify signature here sig.initVerify(x509Certificate.getPublicKey()); sig.update(messageBytes); boolean verifies = sig.verify(sigBytes); log.debug("signature verifies in test: " + verifies); // just call verifySignature method and expect to not throw service.verifySignature(message, signature); }
From source file:test.unit.be.fedict.eid.applet.service.SignatureDataMessageHandlerTest.java
public void testHandleMessage() throws Exception { // setup/*from ww w . j a v a2 s . c om*/ 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(null); EasyMock.expect(mockServletConfig.getInitParameter("SignatureService")).andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter("SignatureServiceClass")) .andStubReturn(SignatureTestService.class.getName()); 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(document); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; // prepare EasyMock.replay(mockServletConfig, mockHttpSession, mockServletRequest); // operate AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession); // verify EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest); assertEquals(signatureValue, SignatureTestService.getSignatureValue()); }
From source file:test.unit.be.fedict.eid.applet.service.SignatureDataMessageHandlerTest.java
public void testHandleMessageWithAudit() throws Exception { // setup/* w w w . ja v a2 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,SERIALNUMBER=1234", 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()); 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(document); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; // prepare EasyMock.replay(mockServletConfig, mockHttpSession, mockServletRequest); // operate AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession); // verify EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest); assertEquals(signatureValue, SignatureTestService.getSignatureValue()); assertEquals("1234", AuditTestService.getAuditSigningUserId()); }
From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java
private PKIMessage buildCertBasedPKIProtection(PKIMessage pKIMessage, CMPCertificate[] extraCerts, PrivateKey key, String digestAlg, String provider, boolean verbose) throws NoSuchProviderException, NoSuchAlgorithmException, SecurityException, SignatureException, InvalidKeyException { // Select which signature algorithm we should use for the response, based on the digest algorithm and key type. ASN1ObjectIdentifier oid = AlgorithmTools.getSignAlgOidFromDigestAndKey(digestAlg, key.getAlgorithm()); if (verbose) { log.info("Selected signature alg oid: " + oid.getId() + ", key algorithm: " + key.getAlgorithm()); }//from www .j a v a 2s . c o m // According to PKCS#1 AlgorithmIdentifier for RSA-PKCS#1 has null Parameters, this means a DER Null (asn.1 encoding of null), not Java null. // For the RSA signature algorithms specified above RFC3447 states "...the parameters MUST be present and MUST be NULL." PKIHeaderBuilder headerBuilder = getHeaderBuilder(pKIMessage.getHeader()); AlgorithmIdentifier pAlg = null; if ("RSA".equalsIgnoreCase(key.getAlgorithm())) { pAlg = new AlgorithmIdentifier(oid, DERNull.INSTANCE); } else { pAlg = new AlgorithmIdentifier(oid); } headerBuilder.setProtectionAlg(pAlg); // Most PKCS#11 providers don't like to be fed an OID as signature algorithm, so // we use BC classes to translate it into a signature algorithm name instead PKIHeader head = headerBuilder.build(); String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid); if (verbose) { log.info("Signing CMP message with signature alg: " + signatureAlgorithmName); } Signature sig = Signature.getInstance(signatureAlgorithmName, provider); sig.initSign(key); sig.update(getProtectedBytes(head, pKIMessage.getBody())); if ((extraCerts != null) && (extraCerts.length > 0)) { pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()), extraCerts); } else { pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign())); } return pKIMessage; }
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. ja va2 s . co 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
public void testHandleMessagePSS() throws Exception { // setup//from w w w . j a v a 2s .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(null); EasyMock.expect(mockServletConfig.getInitParameter("SignatureService")).andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter("SignatureServiceClass")) .andStubReturn(SignatureTestService.class.getName()); 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-PSS"); SignatureDataMessage message = new SignatureDataMessage(); message.certificateChain = new LinkedList<X509Certificate>(); message.certificateChain.add(certificate); Signature signature = Signature.getInstance("SHA1withRSA/PSS", "BC"); signature.initSign(keyPair.getPrivate()); signature.update(document); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; // prepare EasyMock.replay(mockServletConfig, mockHttpSession, mockServletRequest); // operate AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession); // verify EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest); assertEquals(signatureValue, SignatureTestService.getSignatureValue()); }