List of usage examples for java.security Signature update
public final void update(ByteBuffer data) throws SignatureException
From source file:com.alfaariss.oa.authentication.remote.AbstractRemoteMethod.java
/** * Creates a signature over the supplied attributes in the map. * <br>//from ww w . j av a 2 s . c o m * Uses a TreeSet to sort the request parameter names. * @param mapRequest A map containing the attributes to be signed. * @return The signed request attributes. * @throws OAException */ protected String createSignature(Map<String, String> mapRequest) throws OAException { String sSignature = null; try { Signature oSignature = _cryptoManager.getSignature(); if (oSignature == null) { _logger.warn("No signature object found"); throw new OAException(SystemErrors.ERROR_INTERNAL); } StringBuffer sbSignatureData = new StringBuffer(); TreeSet<String> sortedSet = new TreeSet<String>(mapRequest.keySet()); for (Iterator<String> iter = sortedSet.iterator(); iter.hasNext();) { String sKey = iter.next(); sbSignatureData.append(mapRequest.get(sKey)); } PrivateKey keyPrivate = _cryptoManager.getPrivateKey(); if (keyPrivate == null) { _logger.error("No private key available"); throw new OAException(SystemErrors.ERROR_INTERNAL); } oSignature.initSign(keyPrivate); oSignature.update(sbSignatureData.toString().getBytes(CHARSET)); byte[] baSignature = oSignature.sign(); byte[] baEncSignature = Base64.encodeBase64(baSignature); sSignature = new String(baEncSignature, CHARSET); } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Could not create signature for data: " + mapRequest, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } return sSignature; }
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();// w w w . j a va 2 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.logout.LogoutManager.java
private String createSignature(Map<String, String> mapRequest) throws OAException { String sSignature = null;/*ww w . j a v a2 s . c om*/ try { if (_cryptoManager == null) { _logger.warn("No crypto manager available"); throw new OAException(SystemErrors.ERROR_INTERNAL); } Signature signature = _cryptoManager.getSignature(); if (signature == null) { _logger.warn("No signature object found"); throw new OAException(SystemErrors.ERROR_INTERNAL); } StringBuffer sbSignatureData = new StringBuffer(); TreeSet<String> sortedSet = new TreeSet<String>(mapRequest.keySet()); for (Iterator<String> iter = sortedSet.iterator(); iter.hasNext();) { String sKey = iter.next(); sbSignatureData.append(mapRequest.get(sKey)); } PrivateKey keyPrivate = _cryptoManager.getPrivateKey(); if (keyPrivate == null) { _logger.error("No private key available"); throw new OAException(SystemErrors.ERROR_INTERNAL); } signature.initSign(keyPrivate); signature.update(sbSignatureData.toString().getBytes(ASelectProcessor.CHARSET)); byte[] baSignature = signature.sign(); byte[] baEncSignature = Base64.encodeBase64(baSignature); sSignature = new String(baEncSignature, ASelectProcessor.CHARSET); } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Could not create signature for data: " + mapRequest, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } return sSignature; }
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();//from w ww.ja v a2s .c om } 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:com.alfaariss.oa.authentication.remote.aselect.logout.LogoutManager.java
private String createSignature(Map<String, String> mapRequest) throws OAException { String sSignature = null;/* w ww .j a v a 2s . c om*/ try { if (_cryptoManager == null) { _logger.warn("No crypto manager available"); throw new OAException(SystemErrors.ERROR_INTERNAL); } Signature signature = _cryptoManager.getSignature(); if (signature == null) { _logger.warn("No signature object found"); throw new OAException(SystemErrors.ERROR_INTERNAL); } StringBuffer sbSignatureData = new StringBuffer(); TreeSet<String> sortedSet = new TreeSet<String>(mapRequest.keySet()); for (Iterator<String> iter = sortedSet.iterator(); iter.hasNext();) { String sKey = iter.next(); sbSignatureData.append(mapRequest.get(sKey)); } PrivateKey keyPrivate = _cryptoManager.getPrivateKey(); if (keyPrivate == null) { _logger.error("No private key available"); throw new OAException(SystemErrors.ERROR_INTERNAL); } signature.initSign(keyPrivate); signature.update(sbSignatureData.toString().getBytes(CHARSET)); byte[] baSignature = signature.sign(); byte[] baEncSignature = Base64.encodeBase64(baSignature); sSignature = new String(baEncSignature, CHARSET); } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Could not create signature for data: " + mapRequest, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } return sSignature; }
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 ww. j a va 2 s . c o m * @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); } }
From source file:com.tremolosecurity.proxy.auth.SAML2Auth.java
private String procLogoutResp(HttpServletRequest request, HttpServletResponse response, DocumentBuilderFactory factory, String saml, String relayState, String url) throws ParserConfigurationException, SAXException, IOException, UnmarshallingException, Exception, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, ServletException {// ww w .jav a2 s . com LogoutResponseUnmarshaller marshaller = new LogoutResponseUnmarshaller(); DocumentBuilder builder = factory.newDocumentBuilder(); Element root = builder.parse(new InputSource(new StringReader(saml))).getDocumentElement(); LogoutResponse logout = (LogoutResponse) marshaller.unmarshall(root); String issuer = logout.getIssuer().getValue(); boolean found = false; String algType = null; String logoutURL = null; String sigKeyName = null; //Search for the right mechanism configuration for (String chainname : cfgMgr.getAuthChains().keySet()) { AuthChainType act = cfgMgr.getAuthChains().get(chainname); for (AuthMechType amt : act.getAuthMech()) { for (ParamType pt : amt.getParams().getParam()) { if (pt.getName().equalsIgnoreCase("entityID") && pt.getValue().equalsIgnoreCase(issuer)) { //found the correct mechanism found = true; for (ParamType ptx : amt.getParams().getParam()) { if (ptx.getName().equalsIgnoreCase("sigAlg")) { algType = ptx.getValue(); } else if (ptx.getName().equalsIgnoreCase("logoutURL")) { logoutURL = ptx.getValue(); } else if (ptx.getName().equalsIgnoreCase("idpSigKeyName")) { sigKeyName = ptx.getValue(); } } break; } } if (found) { break; } } if (found) { break; } } if (!found) { throw new ServletException("Entity ID '" + issuer + "' not found"); } String authnSig = request.getParameter("Signature"); if (authnSig != null) { String sigAlg = request.getParameter("SigAlg"); StringBuffer query = new StringBuffer(); String qs = request.getQueryString(); query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SAMLResponse")); query.append('&'); query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "RelayState")); query.append('&'); query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SigAlg")); java.security.cert.X509Certificate cert = this.cfgMgr.getCertificate(sigKeyName); String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(algType); if (!sigAlg.equalsIgnoreCase(xmlAlg)) { throw new Exception("Invalid signature algorithm : '" + sigAlg + "'"); } /*if (! logout.getDestination().equals(request.getRequestURL().toString())) { throw new Exception("Invalid destination"); }*/ java.security.Signature sigv = java.security.Signature .getInstance(SAML2Auth.javaDigSigAlgs.get(algType)); 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"); } } response.sendRedirect(logoutURL); return logoutURL; }
From source file:com.tremolosecurity.proxy.auth.SAML2Auth.java
private String procLogoutReq(HttpServletRequest request, HttpServletResponse response, DocumentBuilderFactory factory, String saml, String relayState, String url) throws ParserConfigurationException, SAXException, IOException, UnmarshallingException, Exception, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, ServletException {/* w w w.j a v a 2s .c om*/ LogoutRequestUnmarshaller marshaller = new LogoutRequestUnmarshaller(); DocumentBuilder builder = factory.newDocumentBuilder(); Element root = builder.parse(new InputSource(new StringReader(saml))).getDocumentElement(); org.opensaml.saml.saml2.core.impl.LogoutRequestImpl logout = (org.opensaml.saml.saml2.core.impl.LogoutRequestImpl) marshaller .unmarshall(root); String issuer = logout.getIssuer().getValue(); boolean found = false; String algType = null; String logoutURL = null; String sigKeyName = null; //Search for the right mechanism configuration for (String chainname : cfgMgr.getAuthChains().keySet()) { AuthChainType act = cfgMgr.getAuthChains().get(chainname); for (AuthMechType amt : act.getAuthMech()) { for (ParamType pt : amt.getParams().getParam()) { if (pt.getName().equalsIgnoreCase("entityID") && pt.getValue().equalsIgnoreCase(issuer)) { //found the correct mechanism found = true; for (ParamType ptx : amt.getParams().getParam()) { if (ptx.getName().equalsIgnoreCase("sigAlg")) { algType = ptx.getValue(); } else if (ptx.getName().equalsIgnoreCase("triggerLogoutURL")) { logoutURL = ptx.getValue(); } else if (ptx.getName().equalsIgnoreCase("idpSigKeyName")) { sigKeyName = ptx.getValue(); } } break; } } if (found) { break; } } if (found) { break; } } if (!found) { throw new ServletException("Entity ID '" + issuer + "' not found"); } String authnSig = request.getParameter("Signature"); if (authnSig != null) { String sigAlg = request.getParameter("SigAlg"); StringBuffer query = new StringBuffer(); String qs = request.getQueryString(); query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SAMLRequest")); query.append('&'); if (request.getParameter("RelayState") != null) { query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "RelayState")); query.append('&'); } query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SigAlg")); java.security.cert.X509Certificate cert = this.cfgMgr.getCertificate(sigKeyName); String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(algType); if (!sigAlg.equalsIgnoreCase(xmlAlg)) { throw new Exception("Invalid signature algorithm : '" + sigAlg + "'"); } /*if (! logout.getDestination().equals(request.getRequestURL().toString())) { throw new Exception("Invalid destination"); }*/ java.security.Signature sigv = java.security.Signature .getInstance(SAML2Auth.javaDigSigAlgs.get(algType)); 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"); } } response.sendRedirect(logoutURL); return logoutURL; }
From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java
private void verifyServiceSignature(String serviceSigned, String target, String signatureRequest, String signatureRequestId, String contentType, String language, String relayState, byte[] serviceSignatureValue, List<X509Certificate> serviceCertificateChain) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { LOG.debug("verifying service signature"); X509Certificate serviceCertificate = serviceCertificateChain.get(0); LOG.debug("service identity: " + serviceCertificate.getSubjectX500Principal()); Signature serviceSignature = Signature.getInstance("SHA1withRSA"); serviceSignature.initVerify(serviceCertificate); StringTokenizer serviceSignedStringTokenizer = new StringTokenizer(serviceSigned, ","); while (serviceSignedStringTokenizer.hasMoreTokens()) { String serviceSignedElement = serviceSignedStringTokenizer.nextToken(); LOG.debug("service signed: " + serviceSignedElement); byte[] data; if ("target".equals(serviceSignedElement)) { data = target.getBytes();/*from w w w.ja v a2 s .co m*/ } else if ("SignatureRequest".equals(serviceSignedElement)) { data = signatureRequest.getBytes(); } else if ("SignatureRequestId".equals(serviceSignedElement)) { data = signatureRequestId.getBytes(); } else if ("ContentType".equals(serviceSignedElement)) { data = contentType.getBytes(); } else if ("language".equals(serviceSignedElement)) { data = language.getBytes(); } else if ("RelayState".equals(serviceSignedElement)) { data = relayState.getBytes(); } else { throw new SecurityException("service signed unknown element: " + serviceSignedElement); } serviceSignature.update(data); } boolean valid = serviceSignature.verify(serviceSignatureValue); if (!valid) { throw new SecurityException("service signature not valid"); } }
From source file:de.schlichtherle.xml.GenericCertificate.java
/** * Encodes and signs the given <tt>content</tt> in this certificate and * locks it.//from ww w . j a va 2 s.c o m * <p> * Please note the following: * <ul> * <li>This method will throw a <tt>PropertyVetoException</tt> if this * certificate is already locked, i.e. if it has been signed or * verified before.</li> * <li>Because this method locks this certificate, a subsequent call to * {@link #sign(Object, PrivateKey, Signature)} or * {@link #verify(PublicKey, Signature)} is redundant * and will throw a <tt>PropertyVetoException</tt>. * Use {@link #isLocked()} to detect whether a * generic certificate has been successfuly signed or verified before * or call {@link #getContent()} and expect an * Exception to be thrown if it hasn't.</li> * <li>There is no way to unlock this certificate. * Call the copy constructor of {@link GenericCertificate} if you * need an unlocked copy of the certificate.</li> * </ul> * * @param content The object to sign. This must either be a JavaBean or an * instance of any other class which is supported by * <tt>{@link PersistenceService}</tt> * - maybe <tt>null</tt>. * @param signingKey The private key for signing * - may <em>not</em> be <tt>null</tt>. * @param signingEngine The signature signing engine * - may <em>not</em> be <tt>null</tt>. * * @throws NullPointerException If the preconditions for the parameters * do not hold. * @throws GenericCertificateIsLockedException If this certificate is * already locked by signing or verifying it before. * Note that this is actually a subclass of * {@link PropertyVetoException}. * @throws PropertyVetoException If locking the certifificate (and thus * signing the object) is vetoed by any listener. * @throws PersistenceServiceException If the object cannot be serialised. * @throws InvalidKeyException If the verification key is invalid. */ public synchronized final void sign(final Object content, final PrivateKey signingKey, final Signature signingEngine) throws NullPointerException, GenericCertificateIsLockedException, PropertyVetoException, PersistenceServiceException, InvalidKeyException { // Check parameters. if (signingKey == null) throw new NullPointerException("signingKey"); if (signingEngine == null) throw new NullPointerException("signingEngine"); // Check lock status. final PropertyChangeEvent evt = new PropertyChangeEvent(this, "locked", Boolean.valueOf(isLocked()), Boolean.TRUE); // NOI18N if (isLocked()) throw new GenericCertificateIsLockedException(evt); // Notify vetoable listeners and give them a chance to veto. fireVetoableChange(evt); try { // Encode the object. final byte[] beo = PersistenceService.store2ByteArray(content); // Sign the byte encoded object. signingEngine.initSign(signingKey); signingEngine.update(beo); final byte[] b64es = Base64.encodeBase64(signingEngine.sign()); // the base64 encoded signature final String signature = new String(b64es, 0, b64es.length, BASE64_CHARSET); // Store results. setEncoded(new String(beo, XML_CHARSET)); setSignature(signature); setSignatureAlgorithm(signingEngine.getAlgorithm()); setSignatureEncoding(SIGNATURE_ENCODING); // NOI18N } catch (UnsupportedEncodingException cannotHappen) { throw new AssertionError(cannotHappen); } catch (SignatureException cannotHappen) { throw new AssertionError(cannotHappen); } // Lock this certificate and notify property change listeners. this.locked = true; firePropertyChange(evt); }