List of usage examples for java.security Signature initVerify
public final void initVerify(Certificate certificate) throws InvalidKeyException
From source file:org.structr.util.StructrLicenseManager.java
private boolean isValid(final Map<String, String> properties) { if (!licensePresent) { return false; }/*from w w w . j a v a 2 s . co m*/ final String src = collectLicenseFieldsForSignature(properties); final String name = properties.get(NameKey); final String key = properties.get(SignatureKey); final String hostId = properties.get(MachineKey); final String thisHostId = createHash(); final String edition = properties.get(EditionKey); final String modules = properties.get(ModulesKey); final String dateString = properties.get(DateKey); final String startDateString = properties.get(StartKey); final String endDateString = properties.get(EndKey); final String serversString = properties.get(ServersKey); final Date now = new Date(); if (StringUtils.isEmpty(key)) { logger.error("Unable to read key from license file."); return false; } try { final byte[] data = src.getBytes(CharSet); final Signature signer = Signature.getInstance(SignatureAlgorithm); final byte[] signature = Hex.decodeHex(key.toCharArray()); signer.initVerify(certificate); signer.update(data); if (!signer.verify(signature)) { logger.error("License signature verification failed, license is not valid."); return false; } } catch (Throwable t) { logger.error("Unable to verify license.", t); return false; } if (StringUtils.isEmpty(name)) { logger.error("License file doesn't contain licensee name."); return false; } if (StringUtils.isEmpty(edition)) { logger.error("License file doesn't contain edition."); return false; } if (StringUtils.isEmpty(modules)) { logger.error("License file doesn't contain modules."); return false; } if (StringUtils.isEmpty(hostId)) { logger.error("License file doesn't contain host ID."); return false; } if (StringUtils.isEmpty(dateString)) { logger.error("License file doesn't contain license date."); return false; } if (StringUtils.isEmpty(startDateString)) { logger.error("License file doesn't contain start date."); return false; } if (StringUtils.isEmpty(endDateString)) { logger.error("License file doesn't contain end date."); return false; } // verify host ID if (!thisHostId.equals(hostId) && !"*".equals(hostId)) { logger.error("Host ID found in license ({}) file does not match current host ID.", hostId); return false; } if ("*".equals(hostId)) { // check volume license against server addresses if (StringUtils.isNotBlank(serversString)) { // send HostID to server properties.put(HostIdKey, thisHostId); return checkVolumeLicense(properties, serversString); } final Calendar issuedAtPlusOneMonth = GregorianCalendar.getInstance(); final Calendar cal = GregorianCalendar.getInstance(); // set issuedAt to license date plus one month issuedAtPlusOneMonth.setTime(parseDate(dateString)); issuedAtPlusOneMonth.add(Calendar.MONTH, 1); // check that the license file was issued not more than one month ago if (cal.after(issuedAtPlusOneMonth)) { logger.error( "Development license found in license file is not valid any more, license period ended {}.", format.format(issuedAtPlusOneMonth.getTime())); return false; } } // verify that the license is valid for the current date final Date startDate = parseDate(startDateString); if (startDate != null && now.before(startDate) && !now.equals(startDate)) { logger.error("License found in license file is not yet valid, license period starts {}.", format.format(startDate.getTime())); return false; } // verify that the license is valid for the current date final Date endDate = parseDate(endDateString); if (endDate != null && now.after(endDate) && !now.equals(endDate)) { logger.error("License found in license file is not valid any more, license period ended {}.", format.format(endDate.getTime())); return false; } return true; }
From source file:zlicense.de.schlichtherle.xml.GenericCertificate.java
public final synchronized void verify(PublicKey paramPublicKey, Signature paramSignature) throws NullPointerException, GenericCertificateIsLockedException, PropertyVetoException, InvalidKeyException, SignatureException, GenericCertificateIntegrityException { if (paramPublicKey == null) { throw new NullPointerException("verificationKey"); }//from www . ja va2 s.com if (paramSignature == null) { throw new NullPointerException("verificationEngine"); } PropertyChangeEvent localPropertyChangeEvent = new PropertyChangeEvent(this, "locked", Boolean.valueOf(isLocked()), Boolean.TRUE); if (isLocked()) { throw new GenericCertificateIsLockedException(localPropertyChangeEvent); } fireVetoableChange(localPropertyChangeEvent); try { byte[] arrayOfByte1 = getEncoded().getBytes("UTF-8"); paramSignature.initVerify(paramPublicKey); paramSignature.update(arrayOfByte1); byte[] arrayOfByte2 = Base64.decodeBase64(getSignature().getBytes("US-ASCII")); if (!paramSignature.verify(arrayOfByte2)) { throw new GenericCertificateIntegrityException(); } setSignatureAlgorithm(paramSignature.getAlgorithm()); setSignatureEncoding("US-ASCII/Base64"); } catch (UnsupportedEncodingException localUnsupportedEncodingException) { throw new AssertionError(localUnsupportedEncodingException); } this.locked = true; firePropertyChange(localPropertyChangeEvent); }
From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java
public Object handleMessage(AuthenticationDataMessage message, Map<String, String> httpHeaders, HttpServletRequest request, HttpSession session) throws ServletException { LOG.debug("authentication data message received"); if (null == message.authnCert) { /*//from www . j av a 2 s.c o m * Can be the case for future (Kids) eID cards that have some * certificates missing. */ String msg = "authentication certificate not present"; LOG.warn(msg); throw new ServletException(msg); } byte[] signatureValue = message.signatureValue; LOG.debug("authn signing certificate subject: " + message.authnCert.getSubjectX500Principal()); PublicKey signingKey = message.authnCert.getPublicKey(); if (this.sessionIdChannelBinding) { checkSessionIdChannelBinding(message, request); if (null == this.serverCertificate) { LOG.warn("adviced to use in combination with server certificate channel binding"); } } ChannelBindingService channelBindingService = this.channelBindingServiceLocator.locateService(); if (null != this.serverCertificate || null != channelBindingService) { LOG.debug("using server certificate channel binding"); } if (false == this.sessionIdChannelBinding && null == this.serverCertificate && null == channelBindingService) { LOG.warn("not using any secure channel binding"); } byte[] challenge; try { challenge = AuthenticationChallenge.getAuthnChallenge(session, this.maxMaturity); } catch (SecurityException e) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.authenticationError(remoteAddress, message.authnCert); } throw new ServletException("security error: " + e.getMessage(), e); } byte[] serverCertificateClientPOV = null; try { if (null != message.serverCertificate) { serverCertificateClientPOV = message.serverCertificate.getEncoded(); } } catch (CertificateEncodingException e) { throw new ServletException("server cert decoding error: " + e.getMessage(), e); } /* * We validate the authentication contract using the client-side * communicated server SSL certificate in case of secure channel * binding. */ AuthenticationContract authenticationContract = new AuthenticationContract(message.saltValue, this.hostname, this.inetAddress, message.sessionId, serverCertificateClientPOV, challenge); byte[] toBeSigned; try { toBeSigned = authenticationContract.calculateToBeSigned(); } catch (IOException e) { throw new ServletException("IO error: " + e.getMessage(), e); } try { Signature signature = Signature.getInstance("SHA1withRSA"); signature.initVerify(signingKey); signature.update(toBeSigned); boolean result = signature.verify(signatureValue); if (false == result) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.authenticationError(remoteAddress, message.authnCert); } throw new SecurityException("authn signature incorrect"); } } catch (NoSuchAlgorithmException e) { throw new SecurityException("algo error"); } catch (InvalidKeyException e) { throw new SecurityException("authn key error"); } catch (SignatureException e) { throw new SecurityException("signature error"); } RequestContext requestContext = new RequestContext(session); String transactionMessage = requestContext.getTransactionMessage(); if (null != transactionMessage) { LOG.debug("verifying TransactionMessage signature"); byte[] transactionMessageSignature = message.transactionMessageSignature; if (null == transactionMessageSignature) { throw new SecurityException("missing TransactionMessage signature"); } try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, signingKey); byte[] signatureDigestInfoValue = cipher.doFinal(transactionMessageSignature); ASN1InputStream aIn = new ASN1InputStream(signatureDigestInfoValue); DigestInfo signatureDigestInfo = new DigestInfo((ASN1Sequence) aIn.readObject()); if (false == PLAIN_TEXT_DIGEST_ALGO_OID .equals(signatureDigestInfo.getAlgorithmId().getObjectId().getId())) { throw new SecurityException("TransactionMessage signature algo OID incorrect"); } if (false == Arrays.equals(transactionMessage.getBytes(), signatureDigestInfo.getDigest())) { throw new SecurityException("signed TransactionMessage incorrect"); } LOG.debug("TransactionMessage signature validated"); } catch (Exception e) { LOG.error("error verifying TransactionMessage signature", e); AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.authenticationError(remoteAddress, message.authnCert); } throw new SecurityException("error verifying TransactionMessage signature: " + e.getMessage()); } } /* * Secure channel binding verification. */ if (null != channelBindingService) { X509Certificate serverCertificate = channelBindingService.getServerCertificate(); if (null == serverCertificate) { LOG.warn("could not verify secure channel binding as the server does not know its identity yet"); } else { if (false == serverCertificate.equals(message.serverCertificate)) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.authenticationError(remoteAddress, message.authnCert); } throw new SecurityException("secure channel binding identity mismatch"); } LOG.debug("secure channel binding verified"); } } else { if (null != this.serverCertificate) { if (false == this.serverCertificate.equals(message.serverCertificate)) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.authenticationError(remoteAddress, message.authnCert); } throw new SecurityException("secure channel binding identity mismatch"); } LOG.debug("secure channel binding verified"); } } AuthenticationService authenticationService = this.authenticationServiceLocator.locateService(); List<X509Certificate> certificateChain = new LinkedList<X509Certificate>(); certificateChain.add(message.authnCert); certificateChain.add(message.citizenCaCert); certificateChain.add(message.rootCaCert); certificateChain.add(message.rrnCertificate); try { authenticationService.setHttpSessionObject(request.getSession()); authenticationService.validateCertificateChain(certificateChain); } catch (ExpiredCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } catch (RevokedCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } catch (TrustCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } catch (CertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE); } catch (Exception e) { /* * We don't want to depend on the full JavaEE profile in this * artifact. */ if ("javax.ejb.EJBException".equals(e.getClass().getName())) { Exception exception; try { Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException", new Class[] {}); exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {}); } catch (Exception e2) { LOG.debug("error: " + e.getMessage(), e); throw new SecurityException("error retrieving the root cause: " + e2.getMessage()); } if (exception instanceof ExpiredCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } if (exception instanceof RevokedCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } if (exception instanceof TrustCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } if (exception instanceof CertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE); } } throw new SecurityException("authn service error: " + e.getMessage()); } String userId = UserIdentifierUtil.getUserId(message.authnCert); LOG.info("authenticated: " + userId + " @ " + request.getRemoteAddr()); if (null != this.nrcidSecret) { userId = UserIdentifierUtil.getNonReversibleCitizenIdentifier(userId, this.nrcidOrgId, this.nrcidAppId, this.nrcidSecret); } /* * Some people state that you cannot use the national register number * without hashing. Problem is that hashing introduces hash collision * problems. The probability is very low, but what if it's your leg * they're cutting of because of a patient mismatch based on the SHA1 of * your national register number? */ /* * Push authenticated used Id into the HTTP session. */ session.setAttribute(AUTHENTICATED_USER_IDENTIFIER_SESSION_ATTRIBUTE, userId); EIdData eidData = (EIdData) session.getAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE); if (null == eidData) { eidData = new EIdData(); session.setAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE, eidData); } eidData.identifier = userId; AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { auditService.authenticated(userId); } boolean includeIdentity = requestContext.includeIdentity(); boolean includeAddress = requestContext.includeAddress(); boolean includeCertificates = requestContext.includeCertificates(); boolean includePhoto = requestContext.includePhoto(); /* * Also process the identity data in case it was requested. */ if (includeIdentity) { if (null == message.identityData) { throw new ServletException("identity data not included while requested"); } } if (includeAddress) { if (null == message.addressData) { throw new ServletException("address data not included while requested"); } } if (includePhoto) { if (null == message.photoData) { throw new ServletException("photo data not included while requested"); } } IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator.locateService(); if (null != identityIntegrityService) { if (null == message.rrnCertificate) { throw new ServletException("national registry certificate not included while requested"); } List<X509Certificate> rrnCertificateChain = new LinkedList<X509Certificate>(); rrnCertificateChain.add(message.rrnCertificate); rrnCertificateChain.add(message.rootCaCert); try { identityIntegrityService.checkNationalRegistrationCertificate(rrnCertificateChain); } catch (ExpiredCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } catch (RevokedCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } catch (TrustCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } catch (CertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE); } catch (Exception e) { if ("javax.ejb.EJBException".equals(e.getClass().getName())) { Exception exception; try { Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException", new Class[] {}); exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {}); } catch (Exception e2) { LOG.debug("error: " + e.getMessage(), e); throw new SecurityException("error retrieving the root cause: " + e2.getMessage()); } if (exception instanceof ExpiredCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } if (exception instanceof RevokedCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } if (exception instanceof TrustCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } if (exception instanceof CertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE); } } throw new SecurityException("error checking the NRN certificate: " + e.getMessage(), e); } PublicKey rrnPublicKey = message.rrnCertificate.getPublicKey(); if (includeIdentity) { if (null == message.identitySignatureData) { throw new ServletException("identity signature data not included while requested"); } verifySignature(message.rrnCertificate.getSigAlgName(), message.identitySignatureData, rrnPublicKey, request, message.identityData); } if (includeAddress) { if (null == message.addressSignatureData) { throw new ServletException("address signature data not included while requested"); } byte[] addressFile = trimRight(message.addressData); verifySignature(message.rrnCertificate.getSigAlgName(), message.addressSignatureData, rrnPublicKey, request, addressFile, message.identitySignatureData); } } if (includeIdentity) { Identity identity = TlvParser.parse(message.identityData, Identity.class); if (false == UserIdentifierUtil.getUserId(message.authnCert).equals(identity.nationalNumber)) { throw new ServletException("national number mismatch"); } session.setAttribute(IdentityDataMessageHandler.IDENTITY_SESSION_ATTRIBUTE, identity); eidData.identity = identity; auditService = this.auditServiceLocator.locateService(); if (null != auditService) { auditService.identified(identity.nationalNumber); } } if (includeAddress) { Address address = TlvParser.parse(message.addressData, Address.class); session.setAttribute(IdentityDataMessageHandler.ADDRESS_SESSION_ATTRIBUTE, address); eidData.address = address; } if (includePhoto) { if (includeIdentity) { byte[] expectedPhotoDigest = eidData.identity.photoDigest; byte[] actualPhotoDigest = digestPhoto(getDigestAlgo(expectedPhotoDigest.length), message.photoData); if (false == Arrays.equals(expectedPhotoDigest, actualPhotoDigest)) { throw new ServletException("photo digest incorrect"); } } session.setAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE, message.photoData); eidData.photo = message.photoData; } if (includeCertificates) { if (includeIdentity) { eidData.certs = new EIdCertsData(); eidData.certs.authn = message.authnCert; eidData.certs.ca = message.citizenCaCert; eidData.certs.root = message.rootCaCert; eidData.certs.sign = message.signCert; } session.setAttribute(IdentityDataMessageHandler.AUTHN_CERT_SESSION_ATTRIBUTE, message.authnCert); session.setAttribute(IdentityDataMessageHandler.CA_CERT_SESSION_ATTRIBUTE, message.citizenCaCert); session.setAttribute(IdentityDataMessageHandler.ROOT_CERT_SESSION_ATTRIBTUE, message.rootCaCert); session.setAttribute(IdentityDataMessageHandler.SIGN_CERT_SESSION_ATTRIBUTE, message.signCert); } if (this.includeDataFiles) { session.setAttribute(IdentityDataMessageHandler.EID_DATA_IDENTITY_SESSION_ATTRIBUTE, message.identityData); session.setAttribute(IdentityDataMessageHandler.EID_DATA_ADDRESS_SESSION_ATTRIBUTE, message.addressData); } AuthenticationSignatureService authenticationSignatureService = this.authenticationSignatureServiceLocator .locateService(); if (null != authenticationSignatureService) { List<X509Certificate> authnCertificateChain; if (null != message.authnCert) { authnCertificateChain = new LinkedList<X509Certificate>(); authnCertificateChain.add(message.authnCert); authnCertificateChain.add(message.citizenCaCert); authnCertificateChain.add(message.rootCaCert); authnCertificateChain.add(message.rrnCertificate); } else { authnCertificateChain = null; } AuthenticationSignatureContext authenticationSignatureContext = new AuthenticationSignatureContextImpl( session); PreSignResult preSignResult = authenticationSignatureService.preSign(authnCertificateChain, authenticationSignatureContext); if (null == preSignResult) { return new FinishedMessage(); } boolean logoff = preSignResult.getLogoff(); byte[] computedDigestValue = preSignResult.getDigestInfo().digestValue; String digestAlgo = preSignResult.getDigestInfo().digestAlgo; String authnMessage = preSignResult.getDigestInfo().description; AuthSignRequestMessage authSignRequestMessage = new AuthSignRequestMessage(computedDigestValue, digestAlgo, authnMessage, logoff); return authSignRequestMessage; } return new FinishedMessage(); }
From source file:org.ejbca.core.protocol.cmp.EndEntityCertAuthModuleTest.java
/** * 1- Sends a CRMF request signed by RA1Admin to RA1. Expected: Success * 2- Sends a CRMF request signed by RA2Admin to RA2. Expected: Success * //from w w w .j a va 2 s . c o m * @throws Exception */ @Test public void test01RA1SuccessfullCRMF() throws Exception { // Send CRMF message signed by RA1Admin to RA1 String testUsername = "ra1testuser"; String fingerprintCert = null; try { final X500Name testUserDN = new X500Name("CN=" + testUsername); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(ca1.getSubjectDN(), testUserDN, keys, ca1.getCACertificate(), nonce, transid, false, null, null, null, null, pAlg, new DEROctetString(nonce)); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(ra1admincert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Signing CMP message failed", msg); //******************************************'''''' final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(ra1admincert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, RA1_ALIAS); checkCmpResponseGeneral(resp, ca1.getSubjectDN(), testUserDN, ca1.getCACertificate(), msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert = checkCmpCertRepMessage(testUserDN, (X509Certificate) ca1.getCACertificate(), resp, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert); fingerprintCert = CertTools.getFingerprintAsString(cert); } finally { internalCertStoreSession.removeCertificate(fingerprintCert); endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused); } // Send CRMF message signed by RA2Admin to RA2 testUsername = "ra2testuser"; try { final X500Name testUserDN = new X500Name("CN=" + testUsername); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(ca2.getSubjectDN(), testUserDN, keys, ca2.getCACertificate(), nonce, transid, false, null, null, null, null, pAlg, new DEROctetString(nonce)); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(ra2admincert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra2adminkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Signing CMP message failed.", msg); //******************************************'''''' final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(ra2admincert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, RA2_ALIAS); checkCmpResponseGeneral(resp, ca2.getSubjectDN(), testUserDN, ca2.getCACertificate(), msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert = checkCmpCertRepMessage(testUserDN, (X509Certificate) ca2.getCACertificate(), resp, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert); fingerprintCert = CertTools.getFingerprintAsString(cert); } finally { internalCertStoreSession.removeCertificate(fingerprintCert); endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused); } }
From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java
@Override public void verifySignature(String message, String signature) throws IllegalStateException { Validate.notNull(this.getCheckAlgorithm()); Validate.notNull(this.getCertPath()); boolean verifies = false; try {//from ww w . j a va2 s . com /* create a Signature object and initialize it with the public key */ Signature sig = Signature.getInstance(this.getCheckAlgorithm().getAlgorithmName()); X509Certificate[] chain = this.getCertPath().getCertificates().toArray(new X509Certificate[0]); for (int i = 0; i < chain.length && !verifies; i++) { sig.initVerify(chain[i].getPublicKey()); /* add buffer to verify */ byte[] buffer = message.getBytes("UTF-8"); sig.update(buffer); byte[] sigToVerify = Base64.decode(signature); verifies = sig.verify(sigToVerify); if (!verifies) { log.error("Unable to verify the signature, message " + message + ", sigAlg " + this.getCheckAlgorithm().getAlgorithmName() + ", signature " + signature); } } log.debug("signature verifies: {}", verifies); } catch (Exception e) { log.error("Caught exception while verifying signature, message: " + message + ", sigAlg " + this.getCheckAlgorithm().getAlgorithmName() + ", signature " + signature); log.error("Exception is: {}", e.toString()); throw new IllegalStateException(e); } if (!verifies) { throw new IllegalStateException("Signature verification failed."); } }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Testing a key pair to verify that it is possible to first sign and then verify with it. * //from w ww .j a v a 2 s . com * @param priv * private key to sign a string with * @param pub * public key to verify the signature with * @param provider * A provider used for signing with the private key, or null if "BC" should be used. * * @throws InvalidKeyException * if the public key can not be used to verify a string signed by the private key, because the key is wrong or the signature operation * fails for other reasons such as a NoSuchAlgorithmException or SignatureException. * @throws NoSuchProviderException * if the provider is not installed. */ public static void testKey(final PrivateKey priv, final PublicKey pub, final String provider) throws InvalidKeyException { // NOPMD:this is not a junit test final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes(); final byte signBV[]; final String testSigAlg; { final Iterator<String> i = AlgorithmTools.getSignatureAlgorithms(pub).iterator(); final String tmp = i.hasNext() ? i.next() : null; testSigAlg = tmp != null ? tmp : "SHA1WithRSA"; } if (log.isDebugEnabled()) { log.debug("Testing keys with algorithm: " + pub.getAlgorithm()); log.debug("testSigAlg: " + testSigAlg); log.debug("provider: " + provider); log.trace("privateKey: " + priv); log.trace("privateKey class: " + priv.getClass().getName()); log.trace("publicKey: " + pub); log.trace("publicKey class: " + pub.getClass().getName()); } try { { final Provider prov = Security.getProvider(provider != null ? provider : "BC"); final Signature signature = Signature.getInstance(testSigAlg, prov); signature.initSign(priv); signature.update(input); signBV = signature.sign(); if (signBV == null) { throw new InvalidKeyException("Result from signing is null."); } if (log.isDebugEnabled()) { log.trace("Created signature of size: " + signBV.length); log.trace("Created signature: " + new String(Hex.encode(signBV))); } } { Signature signature; try { signature = Signature.getInstance(testSigAlg, "BC"); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } signature.initVerify(pub); signature.update(input); if (!signature.verify(signBV)) { throw new InvalidKeyException("Not possible to sign and then verify with key pair."); } } } catch (NoSuchAlgorithmException e) { throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e); } catch (SignatureException e) { throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e); } }
From source file:test.be.fedict.eid.applet.PcscTest.java
@Test public void pcscAuthnSignature() throws Exception { this.messages = new Messages(Locale.GERMAN); PcscEid pcscEid = new PcscEid(new TestView(), this.messages); if (false == pcscEid.isEidPresent()) { LOG.debug("insert eID card"); pcscEid.waitForEidPresent();// w ww . j a va 2 s . c o m } byte[] challenge = "hello world".getBytes(); byte[] signatureValue; List<X509Certificate> authnCertChain; try { // pcscEid.logoff(); // pcscEid.selectBelpicJavaCardApplet(); signatureValue = pcscEid.signAuthn(challenge); long t0 = System.currentTimeMillis(); pcscEid.signAuthn(challenge); long t1 = System.currentTimeMillis(); LOG.debug("dt: " + (t1 - t0)); authnCertChain = pcscEid.getAuthnCertificateChain(); LOG.debug("key size: " + authnCertChain.get(0).getPublicKey().getEncoded().length * 8); // pcscEid.logoff(); } finally { pcscEid.close(); } Signature signature = Signature.getInstance("SHA1withRSA"); signature.initVerify(authnCertChain.get(0).getPublicKey()); signature.update(challenge); boolean result = signature.verify(signatureValue); assertTrue(result); LOG.debug("sha1 hex: " + DigestUtils.shaHex(authnCertChain.get(0).getPublicKey().getEncoded())); }
From source file:test.be.fedict.eid.applet.PcscTest.java
@Test public void createPSSSignature() throws Exception { this.messages = new Messages(Locale.GERMAN); PcscEid pcscEid = new PcscEid(new TestView(), this.messages); if (false == pcscEid.isEidPresent()) { LOG.debug("insert eID card"); pcscEid.waitForEidPresent();/* w ww . j a v a 2 s . c o m*/ } CardChannel cardChannel = pcscEid.getCardChannel(); byte[] message = "hello world".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); byte[] digest = messageDigest.digest(message); try { CommandAPDU setApdu = new CommandAPDU(0x00, 0x22, 0x41, 0xB6, new byte[] { 0x04, // length of following data (byte) 0x80, // algo ref 0x10, // PKCS1-PSS-SHA1 (byte) 0x84, // tag for private key ref PcscEid.AUTHN_KEY_ID }); ResponseAPDU responseAPDU = cardChannel.transmit(setApdu); assertEquals(0x9000, responseAPDU.getSW()); pcscEid.verifyPin(); CommandAPDU computeDigitalSignatureApdu = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, digest); responseAPDU = cardChannel.transmit(computeDigitalSignatureApdu); assertEquals(0x9000, responseAPDU.getSW()); byte[] signatureValue = responseAPDU.getData(); LOG.debug("signature value length: " + signatureValue.length); List<X509Certificate> authnCertificateChain = pcscEid.getAuthnCertificateChain(); Signature signature = Signature.getInstance("SHA1withRSA/PSS", "BC"); signature.initVerify(authnCertificateChain.get(0).getPublicKey()); signature.update(message); boolean result = signature.verify(signatureValue); assertTrue(result); } finally { pcscEid.close(); } }
From source file:test.be.fedict.eid.applet.PcscTest.java
@Test public void pcscOTPSpike() throws Exception { this.messages = new Messages(Locale.GERMAN); PcscEid pcscEid = new PcscEid(new TestView(), this.messages); if (false == pcscEid.isEidPresent()) { LOG.debug("insert eID card"); pcscEid.waitForEidPresent();/*from www . j a v a2 s .c om*/ } byte[] challenge1 = "123456".getBytes(); byte[] challenge2 = "654321".getBytes(); byte[] signatureValue1; byte[] signatureValue2; List<X509Certificate> authnCertChain; try { signatureValue1 = pcscEid.signAuthn(challenge1); signatureValue2 = pcscEid.signAuthn(challenge2); authnCertChain = pcscEid.getAuthnCertificateChain(); } finally { pcscEid.close(); } byte[] sv1 = Arrays.copyOf(signatureValue1, 13); byte[] sv2 = Arrays.copyOf(signatureValue2, 13); LOG.debug("same encrypted prefix: " + Arrays.equals(sv1, sv2)); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initVerify(authnCertChain.get(0).getPublicKey()); signature.update(challenge1); boolean result = signature.verify(signatureValue1); assertTrue(result); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, authnCertChain.get(0).getPublicKey()); byte[] signatureDigestInfoValue = cipher.doFinal(signatureValue1); LOG.debug("encrypted signature value: " + signatureValue1.length); ASN1InputStream aIn = new ASN1InputStream(signatureDigestInfoValue); DigestInfo signatureDigestInfo = new DigestInfo((ASN1Sequence) aIn.readObject()); LOG.debug("algo OID: " + signatureDigestInfo.getAlgorithmId().getObjectId().getId()); LOG.debug("digest size: " + signatureDigestInfo.getDigest().length); int digestIndex = findSubArray(signatureDigestInfoValue, signatureDigestInfo.getDigest()); assertTrue(-1 != digestIndex); LOG.debug("digest index: " + digestIndex); // inject the encrypted digest of signature1 into signature2 // padding will look bad now System.arraycopy(signatureValue1, 13, signatureValue2, 13, 20); cipher = Cipher.getInstance("RSA/ECB/nopadding"); cipher.init(Cipher.DECRYPT_MODE, authnCertChain.get(0).getPublicKey()); signatureValue2 = Arrays.copyOf(signatureValue2, 13 + 20); byte[] signatureDigestInfoValue2 = cipher.doFinal(signatureValue2); LOG.debug("decrypted structure size: " + signatureDigestInfoValue2.length); signatureDigestInfoValue2 = Arrays.copyOf(signatureDigestInfoValue2, 13 + 20); LOG.debug("decrypted structure size (truncated): " + signatureDigestInfoValue2.length); ASN1InputStream aIn2 = new ASN1InputStream(signatureDigestInfoValue2); DigestInfo signatureDigestInfo2 = new DigestInfo((ASN1Sequence) aIn2.readObject()); LOG.debug("digest size: " + signatureDigestInfo2.getDigest().length); LOG.debug("digest: " + new String(signatureDigestInfo2.getDigest())); }
From source file:com.alfaariss.oa.profile.aselect.processor.handler.AbstractAPIHandler.java
/** * Verifies signatures for requests retrieved from a requestor. * @param sSignature the signature that must be verified * @param sKeyAlias the key alias/*from w w w . jav a2 s. c om*/ * @param sData the signed data * @return TRUE if the signature is valid * @throws ASelectException if verification failed */ protected boolean verifySignature(String sSignature, String sKeyAlias, String sData) throws ASelectException { try { Certificate oCertificate = _cryptoManager.getCertificate(sKeyAlias); if (oCertificate == null) { _logger.warn("No certificate object found with alias: " + sKeyAlias); throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR); } Signature oSignature = _cryptoManager.getSignature(); if (oSignature == null) { _logger.warn("No signature object found"); throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR); } oSignature.initVerify(oCertificate); oSignature.update(sData.getBytes(ASelectProcessor.CHARSET)); byte[] baData = Base64.decodeBase64(sSignature.getBytes(ASelectProcessor.CHARSET)); boolean bVerified = oSignature.verify(baData); if (!bVerified) { StringBuffer sbDebug = new StringBuffer("Could not verify signature '"); sbDebug.append(sSignature); sbDebug.append("' for key with alias '"); sbDebug.append(sKeyAlias); sbDebug.append("' with data: "); sbDebug.append(sData); _logger.debug(sbDebug.toString()); } return bVerified; } catch (CryptoException e) { _logger.warn("A crypto exception occurred", e); throw new ASelectException(e.getMessage()); } catch (ASelectException e) { throw e; } catch (Exception e) { StringBuffer sbError = new StringBuffer("Could not verify signature '"); sbError.append(sSignature); sbError.append("' for key with alias: "); sbError.append(sKeyAlias); _logger.fatal(sbError.toString(), e); throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR); } }