📄 psecredential.java
字号:
if( oldValid != valid ) { support.firePropertyChange( "valid", oldValid, valid ); } } /** * {@inheritDoc} **/ public Object getSubject() { return ((X509Certificate) certs.getCertificates().get(0)).getSubjectDN(); } /** * {@inheritDoc} **/ public Service getSourceService() { return source; } /** * {@inheritDoc} * **/ public StructuredDocument getDocument(MimeMediaType encodeAs ) throws Exception { if( !isValid() ) { throw new javax.security.cert.CertificateException( "Credential is not valid. Cannot generate document."); } if( !local ) { throw new IllegalStateException( "This credential is not a local credential and document cannot be created." ); } StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument( encodeAs, "jxta:Cred" ); if( doc instanceof XMLDocument ) { ((XMLDocument)doc).addAttribute( "xmlns:jxta", "http://jxta.org" ); ((XMLDocument)doc).addAttribute( "xml:space", "preserve" ); } if( doc instanceof Attributable ) { ((Attributable)doc).addAttribute( "type", "jxta:PSECred" ); } Element e; e= doc.createElement( "PeerGroupID", getPeerGroupID().toString() ); doc.appendChild( e ); e = doc.createElement( "PeerID", getPeerID().toString() ); doc.appendChild( e ); // add the Certificate element net.jxta.impl.protocol.Certificate certChain = new net.jxta.impl.protocol.Certificate( ); List certsList = certs.getCertificates(); certChain.setCertificates( certsList ); StructuredDocument certsDoc = (StructuredDocument) certChain.getDocument( encodeAs ); if( certsDoc instanceof Attributable ) { ((Attributable)certsDoc).addAttribute( "type", certsDoc.getKey().toString() ); } StructuredDocumentUtils.copyElements( doc, doc, certsDoc, "Certificate" ); // Add the signature. List someStreams = new ArrayList( 3 ); try { someStreams.add( new ByteArrayInputStream( getPeerGroupID().toString().getBytes( "UTF-8" ) ) ); someStreams.add( new ByteArrayInputStream( getPeerID().toString().getBytes( "UTF-8" ) ) ); Iterator eachCert = certsList.iterator(); while( eachCert.hasNext() ) { X509Certificate aCert = (X509Certificate) eachCert.next(); someStreams.add( new ByteArrayInputStream( aCert.getEncoded() ) ); } InputStream signStream = new SequenceInputStream( Collections.enumeration(someStreams) ); byte [] sig = source.peerSecurityEngine.sign( source.peerSecurityEngine.getSignatureAlgorithm(), this, signStream ); e = doc.createElement( "Signature", PSEUtils.base64Encode(sig) ); doc.appendChild( e ); } catch( java.io.UnsupportedEncodingException never ) { // UTF-8 is always available ; } if( doc instanceof Attributable ) { ((Attributable)doc).addAttribute( "algorithm", source.peerSecurityEngine.getSignatureAlgorithm() ); } return doc; } /** * Returns the certificate associated with this credential. * * @return the certificate associated with this credential. **/ public X509Certificate getCertificate() { return (X509Certificate) certs.getCertificates().get(0); } /** * Returns the certificate chain associated with this credential. * * @return the certificate chain associated with this credential. **/ public X509Certificate [] getCertificateChain() { List certList = certs.getCertificates(); return (X509Certificate []) certList.toArray( new X509Certificate [certList.size()] ); } /** * Set the certificate associated with this credential * * @param cert the certificate associated with this credential. **/ private void setCertificateChain( CertPath certChain ) { certs = certChain; Date now = new Date(); Date becomesValid = ((X509Certificate)certs.getCertificates().get(0)).getNotBefore(); Date expires = ((X509Certificate)certs.getCertificates().get(0)).getNotAfter(); if( becomesValid.compareTo( now ) > 0 ) { if( null != becomesValidTask ) { becomesValidTask.cancel(); } becomesValidTask = new TimerTask() { public void run() { support.firePropertyChange( "expired", false, true ); if( valid ) { support.firePropertyChange( "valid", false, true ); } } }; expirationTimer.schedule( becomesValidTask, becomesValid ); } if( null != expiresTask ) { expiresTask.cancel(); } if( expires.compareTo( now ) > 0 ) { expiresTask = new TimerTask() { public void run() { support.firePropertyChange( "expired", true, false ); if( valid ) { support.firePropertyChange( "valid", true, false ); } } }; expirationTimer.schedule( expiresTask, expires ); } boolean nowGood = (null == becomesValidTask) && (null != expiresTask); support.firePropertyChange( "expired", true, nowGood ); setValid( nowGood ); } /** * Returns the private key associated with this credential. Only valid for * locally generated credentials. * * @deprecated Use <@link #getSigner(String)> or <@link #getSignatureVerifier(String)> instead. * * @return the private key associated with this credential. **/ public PrivateKey getPrivateKey() { if( !local ) { throw new IllegalStateException( "This credential is not a local credential and cannot be used for signing." ); } if( null == privateKey ) { throw new IllegalStateException( "This local credential is engine based and cannot provide the private key." ); } return privateKey; } /** * Sets the private key associated with this credential. * * @param privateKey the private key associated with this credential. **/ private void setPrivateKey( PrivateKey privateKey ) { this.privateKey = privateKey; } /** * Returns the key id associated with this credential, if any. Only locally * generated credentials have a key ID. * * @return Returns the key id associated with this credential, if any. **/ public ID getKeyID() { return keyID; } /** * Sets the key id associated with this credential. **/ private void setKeyID( ID keyID ) { this.keyID = keyID; } /** * Get a Signature object based upon the private key associated with this * credential. * * @param algorithm the signing algorithm to use. * @return Signature. **/ public Signature getSigner( String algorithm ) throws NoSuchAlgorithmException { if( !local ) { throw new IllegalStateException( "This credential is not a local credential and cannot be used for signing." ); } Signature sign = Signature.getInstance( algorithm ); try { sign.initSign( privateKey ); } catch ( java.security.InvalidKeyException failed ) { IllegalStateException failure = new IllegalStateException( "Invalid private key" ); failure.initCause( failed ); throw failure; } return sign; } /** * * /** * Get a Signature verifier object based upon the certificate associated * with this credential. * * @param algorithm the signing algorithm to use. * @return Signature. **/ public Signature getSignatureVerifier( String algorithm ) throws NoSuchAlgorithmException { Signature verify = Signature.getInstance( algorithm ); try { verify.initVerify( (X509Certificate) certs.getCertificates().get(0) ); } catch ( java.security.InvalidKeyException failed ) { IllegalStateException failure = new IllegalStateException( "Invalid certificate" ); failure.initCause( failed ); throw failure; } return verify; } /** * Process an individual element from the document. * * @param elem the element to be processed. * @return true if the element was recognized, otherwise false. **/ protected boolean handleElement( XMLElement elem ) { if( elem.getName().equals("PeerGroupID")) { try { ID pid = IDFactory.fromURI( new URI( elem.getTextValue() ) ); setPeerGroupID( (PeerGroupID) pid ); } catch ( URISyntaxException badID ) { throw new IllegalArgumentException( "Bad PeerGroupID in advertisement: " + elem.getTextValue() ); } catch ( ClassCastException badID ) { throw new IllegalArgumentException( "Id is not a group id: " + elem.getTextValue() ); } return true; } if( elem.getName().equals("PeerID")) { try { ID pid = IDFactory.fromURI( new URI( elem.getTextValue() ) ); setPeerID( (PeerID) pid ); } catch ( URISyntaxException badID ) { throw new IllegalArgumentException( "Bad Peer ID in advertisement: " + elem.getTextValue() ); } catch ( ClassCastException badID ) { throw new IllegalArgumentException( "Id is not a peer id: " + elem.getTextValue() ); } return true; } if( elem.getName().equals("Certificate")) { // XXX Compatibility hack so that net.jxta.impl.protocol.Certificate will recognize element // as a certificate. if( null == elem.getAttribute( "type" ) ) { elem.addAttribute( "type", net.jxta.impl.protocol.Certificate.getMessageType() ); } net.jxta.impl.protocol.Certificate certChain = new net.jxta.impl.protocol.Certificate( elem ); try { CertificateFactory cf = CertificateFactory.getInstance( "X.509" ); certs = cf.generateCertPath( Arrays.asList( certChain.getCertificates() ) ); } catch( java.security.cert.CertificateException failure ) { throw new IllegalArgumentException( "bad certificates in chain." ); } return true; } if( elem.getName().equals( "Signature" ) ) { if( null == certs ) { throw new IllegalArgumentException( "Signature out of order in Credential." ); } List someStreams = new ArrayList( 3 ); try { byte [] signatureToCompare = PSEUtils.base64Decode( new StringReader(elem.getTextValue()) ); someStreams.add( new ByteArrayInputStream( getPeerGroupID().toString().getBytes( "UTF-8" ) ) ); someStreams.add( new ByteArrayInputStream( getPeerID().toString().getBytes( "UTF-8" ) ) ); Iterator eachCert = certs.getCertificates().iterator(); while( eachCert.hasNext() ) { X509Certificate aCert = (X509Certificate) eachCert.next(); someStreams.add( new ByteArrayInputStream( aCert.getEncoded() ) ); } InputStream signStream = new SequenceInputStream( Collections.enumeration(someStreams) ); // FIXME 20051007 bondolo Fix handling of signature type. if( !PSEUtils.verifySignature( "SHA1WITHRSA", getCertificate(), signatureToCompare, signStream ) ) { throw new IllegalArgumentException( "Certificated did not match" ); } } catch ( Throwable failed ) { if (LOG.isEnabledFor(Level.WARN)) { LOG.warn( "Failed to validate signature ", failed ); } throw new IllegalArgumentException( "Failed to validate signature " + failed.getMessage() ); } return true; } // element was not handled return false; } /** * Intialize from a portion of a structured document. **/ protected void initialize( Element root ) { if( !XMLElement.class.isInstance( root ) ) { throw new IllegalArgumentException( getClass().getName() + " only supports XMLElement" ); } XMLElement doc = (XMLElement) root; String typedoctype = ""; Attribute itsType = doc.getAttribute( "type" ); if( null != itsType ) { typedoctype = itsType.getValue(); } String doctype = doc.getName(); if( !doctype.equals("jxta:PSECred") && !typedoctype.equals("jxta:PSECred") ) { throw new IllegalArgumentException( "Could not construct : " + getClass().getName() + "from doc containing a " + doctype ); } Enumeration elements = doc.getChildren(); while (elements.hasMoreElements()) { XMLElement elem = (XMLElement) elements.nextElement(); if( !handleElement( elem ) ) { if (LOG.isEnabledFor(Level.WARN)) { LOG.warn("Unhandled element '" + elem.getName() + "' in " + doc.getName() ); } } } // sanity check time! if( null == getSubject() ) { throw new IllegalArgumentException( "subject was never initialized." ); } if( null == getPeerGroupID() ) { throw new IllegalArgumentException( "peer group was never initialized." ); } if( null == getPeerID() ) { throw new IllegalArgumentException( "peer id was never initialized." ); } if( null == certs ) { throw new IllegalArgumentException( "certificates were never initialized." ); } // FIXME bondolo@jxta.org 20030409 should check for duplicate elements and for peergroup element } public X509Certificate[] generateServiceCertificate( ID assignedID ) throws IOException, KeyStoreException, InvalidKeyException, SignatureException { return source.generateServiceCertificate( assignedID, this ); } public PSECredential getServiceCredential( ID assignedID ) throws IOException, PeerGroupException, InvalidKeyException, SignatureException { return source.getServiceCredential( assignedID, this ); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -