翻译From: http://www.devx.com/Java/Article/28816/1954
实施与Java和WSS4J的WS - Security
eb services have evolved into a standard means for integrating organizations using differing technologies running on heterogeneous systems and frameworks.电子束服务已经演变成一个标准的组织手段结合使用不同的技术对异构系统和框架上运行。 A Web service is a business-logic component designed to be accessed across a network using industry-standard protocols and data formats. Web服务是一个商业逻辑组件设计为通过网络访问使用行业标准协议和数据格式。 A Web service exposes a public interface described by a standard industry document format such as a WSDL file. Web服务公开了一个公共接口标准工业文件格式描述,例如一个WSDL文件。 This description document lets external systems understand and interact with the Web service over standard transport protocols such as HTTP, with messages encapsulated using standard message protocols such as SOAP.这说明文件允许外部系统的了解和互动,对这些标准的传输协议为HTTP的Web服务,例如SOAP封装使用标准邮件协议的消息。
Web services produce loosely-coupled systems that clients typically communicate with in a stateless, asynchronous manner, requiring no concern for the underlying protocol or location of the service. Web服务产生松散的耦合系统,客户沟通的一个典型无国籍,异步的方式,无需对底层协议或服务的位置的关注。 Unfortunately, this loosely-coupled, open communication environment is rife with potential security threats, as the next section illustrates.不幸的是,这个松散的耦合,开放的沟通环境,是充斥着潜在的安全威胁,正如下一节说明。
Web Services Security Threats Web服务安全的威胁
Traditional security technologies are not sufficient for Web services security because of the need to secure data and components on a more granular scale.传统的安全技术是对Web服务的安全性足够,因为需要保证在一个更精细的比例尺数据和组件。 Because Web services use message-based technologies for complex transactions across multiple domains, traditional security processes fall short.因为Web服务的使用复杂的交易,在多个领域,传统的安全流程的信息为基础的技术达不到。 A Web-service message can traverse several intermediaries before it reaches its final destination.一个Web服务消息可以穿越几个中介才到达其最终目的地。 Therefore, the need for sophisticated message-level security becomes a high priority and is not addressed by existing security technologies.因此,对复杂的消息级安全的需要成为一个高度优先事项,而不是由现有的安全技术处理。
The following list illustrates some of the specific Web-services security threats:下面的列表说明了具体的Web服务安全性的一些威胁:
Given these threats, clearly, a secure solution is imperative.鉴于这些威胁,显然,一个安全的解决方案是必不可少的。
Introduction to WS-Security 介绍的WS - Security
The WS-Security standard specifies extensions to SOAP messaging that provide message-level integrity, confidentiality, and authentication.在WS - Security标准规定扩展SOAP消息提供消息级别的完整性,保密性和身份验证。 WS-Security enables collaboration between other Web services security standards and protocols. WS - Security的实现与其他Web服务安全标准和协议的合作。 Because WS-Security does not dictate one specific security technology, the WS-Security specification allows organizations to use heterogeneous security models and encryption technologies, as well as a number of different security tokens.由于WS - Security的没有规定一个具体的安全技术,WS - Security规范允许企业使用异类安全模型和加密技术,以及不同的安全令牌的数量。
The WS-Security specification is concerned with three main area of focus:在WS - Security规范所涉及的三个主要重点领域:
Here's how WS-Security treats these three areas of focus.以下是如何的WS - Security的对待这三个重点领域。
Validating Authentication Claims using Security Tokens 验证使用安全令牌认证索赔
WS-Security uses security tokens to validate authentication assertions made by principals. WS - Security的使用安全令牌来验证身份的校长作出断言。 These assertions are referred to as claims .这些说法被称为索赔 。 Claims can be validated by a message recipient or by an authorized third party, such as a certificate authority.索赔可以通过验证邮件的收件人或由授权的第三方,如证书颁发机构。
You can use two types of security tokens:你可以使用两种类型的安全令牌:
Preserving Message Integrity using XML Signatures 保持消息完整性使用XML签名
WS-Security addresses message integrity (preventing unauthorized message content modification) through XML signatures. WS - Security的地址信息的完整性(防止未经授权的邮件内容修改)通过XML签名。 You can use signatures to:你可以用它来签名:
Preserving Message Confidentiality using XML Encryption 保使用XML加密消息的保密性
WS-Security maintains message confidentiality using XML Encryption in association with security tokens to ensure that sensitive parts of a SOAP message remain confidential. WS - Security的维护与安全令牌协会消息的保密性使用XML加密,以确保SOAP消息的敏感部分保密。
In the rest of this article, you'll see how to create these security tokens, add XML signatures, and add XML encryption to your SOAP messages so that they meet the WS-Security specifications.在本文的其余部分,你将看到如何创建这些安全性令牌,添加XML签名和XML加密添加到您的SOAP消息,使他们达到了WS - Security的规范。
Keystores and the Java Keytool Utility 密钥库和Java keytool工具
Because the WS-Security specification depends on the use of encryption keys and certificates, it's useful to discuss a mechanism to generate and maintain them.由于WS - Security规范对加密密钥和证书的使用取决于它的有益的讨论机制,以生成和维护它们。
You can use the Java keytool utility, which ships with the JDK, to generate public/private key-pairs and certificates and maintain them in a password-protected keystore so that your Java programs can use them.你可以使用Java keytool工具,附带的JDK,生成公共/私人密钥对密钥库和证书,并保持他们在一个受密码保护,让你的Java程序可以使用它们。 A keystore is a standard, password-protected repository, also known as PKCS#12, which you can use to store and transport keys and certificates securely.密钥仓库是一个标准,密码保护的资料库,也为的PKCS#12,你可以用它来存储和运输安全密钥和证书已知的。
Creating a Keystore and Key-Pair 创建keystore和密钥对
The keytool utility can generate a key pair. keytool工具可以生成一个密钥对。 Typically, you must generate two key-pairs to use one as a certificate/public-key for the other; therefore, execute the keytool with the -genkey option twice, and store each distinct key-pair into a separate keystore.通常,您必须生成两个密钥对使用其他一个作为证书/公开密钥的,因此,执行keytool的选项与- genkey两次,并存储到一个单独的密钥库对每个不同的键。
Here's how to use the keytool utility to generate a key-pair as a private key.以下是如何使用keytool实用程序来生成一个密钥作为私钥对。
Author's Note: Enter the command lines shown below on a single line.作者注:输入命令下面一行显示线。 |
%JAVA_HOME%\bin\keytool -genkey -alias privkey -keystore privkeystore -dname "cn=privkey" -keypass foobar -storepass foobar
To generate a key-pair to use as a certificate/public-key, use this code (again, enter the entire command on a single line).要生成一个密钥对使用一个证书/公钥,使用此代码(同样,输入一个单一的整个命令行)。
%JAVA_HOME%\bin\keytool -genkey -alias pubcert -keystore pubcertkeystore -dname "cn=pubcert" -keypass foobar -storepass foobar
The preceding commands前面的命令
To examine the contents of a keystore, execute the keytool utility with the -list option.要检查一个密钥库的内容,执行keytool工具的列表选项与-。 For example, to examine the first ( privkeystore) contents created earlier use:例如,要检查第一(privkeystore)使用以前创建的内容:
%JAVA_HOME%\bin\keytool -list -keystore privkeystore Enter keystore password: foobar Keystore type: jks Keystore provider: SUN Your keystore contains 1 entry privkey, Jul 25, 2005, keyEntry, Certificate fingerprint (MD5): A1:FA:99:E2:A7:E8:1A:FB:D8:B7:87:91:D1:0E:9C:F8
Now, look at the pubcert certificate keystore:现在,看看pubcert证书密钥库:
%JAVA_HOME%\bin\keytool -list -keystore pubcertkeystore Enter keystore password: foobar Keystore type: jks Keystore provider: SUN Your keystore contains 1 entry pubcert, Jul 25, 2005, keyEntry, Certificate fingerprint (MD5): 99:8F:14:C5:BB:21:86:77:D2:CF:56:DE:98:DD:74:62
To examine a key in detail, you can use the keytool utility to display it to the console in RFC 1421 format using the -rfc option, as follows:要仔细研究的一个关键,你可以使用 keytool实用程序来显示它在RFC 1421格式控制台使用- rfc选项,如下:
%JAVA_HOME%\bin\keytool -export -keystore privkeystore -alias privkey -storepass foobar --rfc
You'll see output on the console similar to the following:您将在控制台上看到类似下面的输出:
-----BEGIN CERTIFICATE----- MIIBlTCB/wIEQuWjhTANBgkqhkiG9w0BAQQFADASMRAwDgYDVQQDEwd0ZXN 0a2V5MB4XDTA1MDcyNjAyNDQyMVoXDTA1MTAyNDAyNDQyMVowEjEQMA4GA1 UEAxMHdGVzdGtleTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAz/HFY xicr+vonubY3rgnJFdl6OsvbinR2L54U7WKHNz2w7w3cOvTMGqop/xQtePx k3hXIJFs27OBC28Y8jRKYdgGDYMVU5/V0ddlGQUgfU7Xy9jdIPm61ayu3QH 9LcXYSzVfHNeL3HHRcJV3jSwRs1K/vIVZKLNnBRufe2kORK0CAwEAATANBg kqhkiG9w0BAQQFAAOBgQBWAoAzG5B54dNUt7t3iU98Dre0EI9JkEn8HYiix oJxs1SmI/vESDbuAJY9EbjlPnvhHrgZL3rtb8twwzHwbLhnxVeV/LRk2C2e ghkPPEklp3w+UVv5U3dsvoR6LO4z3fTjnc+YbMG0Iss5gkwxJqYy/6qeyYY 3EGoxl8Ehyu/hOw== -----END CERTIFICATE-----
Self-Signing Certificates 自签名证书
Keys are unusable unless they are signed, but you can use the keytool to self-sign them (for testing purposes only), as follows:键是无法使用的,除非它们已经签署了,但你可以使用 keytool自行签署人(仅用于测试),如下:
%JAVA_HOME%\bin\keytool -selfcert -alias privkey -keystore privkeystore -keypass foobar -storepass foobar
Now, the certificate can be self-signed, as follows:现在,该证书可自签名,如下:
%JAVA_HOME%\bin\keytool -selfcert -alias pubcert -keystore pubcertkeystore -keypass foobar -storepass foobar
Exporting Certificates with the Keytool Utility 导出的证书keytool实用程序
After generating and self-signing the keys/certificates and storing them in the keystores, import each public key into the other key's keystore.后产生和自签名的密钥/证书和存储在其中的密钥库,导入每个公钥到其他关键的密钥库。 This requires two steps: exporting the public key to a certificate file and importing the certificate to the other keystore.这需要两个步骤:导出的公钥证书文件,导入证书到其他密钥库。 To export the public key to a certificate file, use:要导出公钥证书文件,请使用:
%JAVA_HOME%\bin\keytool -export -keystore pubcertkeystore -alias pubcert -storepass foobar -file pubcert
You should see a response that says:您应该看到一个响应,说:
Certificate stored in file <pubcert>
You can also use the keytool utility to display the contents of the certificate file using the -printcert option, as follows:您也可以使用 keytool实用程序来显示证书的内容的文件使用- printcert选项,如下:
%JAVA_HOME%\bin\keytool -printcert -file pubcert
The output will look like:输出将如下所示:
Owner: CN=pubcert Issuer: CN=pubcert Serial number: 42e5b3c4 Valid from: Mon Jul 25 21:53:40 MDT 2005 until: Sun Oct 23 21:53:40 MDT 2005 Certificate fingerprints: MD5: 99:8F:14:C5:BB:21:86:77:D2:CF:56:DE:98:DD:74:62 SHA1: EC:59:92:E9:1F:8A:A6:0A:85:54:EC:76:47:DB:5F:3F:D2:15:78:77
The exported certificate contains the public key and distinguished name given to the certificate (in this case, pubcert ).导出的证书包含公钥和可分辨的名称给予,pubcert证书(在这种情况下)。
Importing Certificates into Keystores 导入证书到密钥库
To import a public certificate into the keystore of the private key, issue the command:要导入的私钥密钥库公共证书,发出命令:
%JAVA_HOME%\bin\keytool -import -alias pubcert -file pubcert -keystore privkeystore -storepass foobar
The output looks like:输出看起来像这样:
Owner: CN=pubcert Issuer: CN=pubcert Serial number: 42e5b3c4 Valid from: Mon Jul 25 21:53:40 MDT 2005 until: Sun Oct 23 21:53:40 MDT 2005 Certificate fingerprints: MD5: 99:8F:14:C5:BB:21:86:77:D2:CF:56:DE:98:DD:74:62 SHA1: EC:59:92:E9:1F:8A:A6:0A:85:54:EC:76:47:DB:5F:3F:D2:15:78:77
Answer the following question:回答下列问题:
Trust this certificate? [no]: yes Certificate was added to keystore
Now that the certificate has been imported into the private key's keystore, you can reexamine the contents of the keystore using the keytool utility with the -list option, as follows:现在,该证书已被导入到keystore中的私钥的,你可以重新审视密钥库的内容,使用keytool实用程序的列表选项与-如下:
%JAVA_HOME%\bin\keytool -list -keystore privkeystore Enter keystore password: foobar
After entering your password you'll see the following output:输入密码后你会看到下面的输出:
Keystore type: jks Keystore provider: SUN Your keystore contains 2 entries privkey, Jul 25, 2005, keyEntry, Certificate fingerprint (MD5): E7:4A:D9:D7:67:A6:6D:E7:A5:C4:28:22:3D:C5:C4:30 pubcert, Jul 25, 2005, trustedCertEntry, Certificate fingerprint (MD5): 99:8F:14:C5:BB:21:86:77:D2:CF:56:DE:98:DD:74:62
As the preceding examples illustrated, there are now two entries in the private-key's keystore.由于前面的例子说明,现在有两个私钥的密钥仓库项。 The first, with the alias testkey , is identified as a key entry.第一次测试键的别名,与是项确定为关键。 The second entry is the certificate from the certificate file.第二项是从证书文件的证书。
At this point you have performed sufficient key management tasks to use the private-key keystore to perform WS-Security tasks using the Apache Web Services Security for Java framework.此时,您有足够的执行管理任务的关键使用私钥的密钥库进行的WS - Security的任务使用的Java框架Apache的Web服务安全性。
Using the WSS4J Framework 使用WSS4J框架
Apache's WSS4J is a Java implementation of the OASIS Web Services Security (WS-Security) specification. Apache的WSS4J是一个与安全的Java实现的OASIS Web服务安全(Web服务)规范。 WSS4J is a framework that you can use to sign and verify SOAP messages with WS-Security information. WSS4J是一个框架,你可以用它来签名和验证的SOAP与WS - Security的信息消息。 WSS4J uses the Apache Axis and Apache XML-Security projects and is interoperable with JAX-RPC server/clients and .NET server/clients. WSS4J使用Apache Axis和Apache XML的安全计划,并使用JAX - RPC的服务器/客户端互通和。NET服务器/客户端。 WSS4J implements Username Token profile V1.0 and X.509 Token Profile V1.0. WSS4J实现用户令牌配置文件V1.0和1.0版的X.509凭证档案。 WSS4J can generate and process the following SOAP Bindings: WSS4J可以生成和处理以下SOAP绑定:
WSS4J can secure Web services deployed in most Java Web services environments; however, it ships with specific support for the Axis Web services framework. WSS4J可以在最安全的环境中部署Java Web服务的Web服务,但是,与对AXIS Web服务框架的具体支持船舶。 You can use WSS4J in a standalone manner or in tandem with Axis to create and process WS-Security elements within a SOAP envelope.你可以使用一个独立的方式WSS4J或与轴的同时,将创建和处理SOAP信封内的WS - Security的元素。 You can obtain the latest release of the WSS4J project by checking out the CVS module, ws-wss4j , using the following CVS path with any CVS client.您可以获取最新版本的模块WSS4J项目通过检查出的CVS中,WS - wss4j,使用下面的CVS客户端与任何CVS的路径。
:pserver:[email protected]:/home/cvspublic.
The tools in the next sections demonstrate how to use WSS4J to generate XML that conforms to the latest WS-Security specification.在下一节的工具演示了如何使用WSS4J生成的XML符合最新的WS - Security规范。
Initializing the WSS4J Framework 初始化WSS4J框架
First, you must initialize the WSS4J framework—in this case, to the default values.首先,你必须初始化WSS4J框架,在这种情况下,为默认值。 For example:例如:
private static final WSSecurityEngine secEngine = new WSSecurityEngine();
Next, create a crypto provider.接下来,创建一个加密提供程序。 The default factory getInstance() method creates a provider according to the class name specified by the system property org.apache.ws.security.crypto.provider .默认的工厂的getInstance()方法创建一个org.apache.ws.security.crypto.provider供应商根据类的属性名指定的系统。 If the provider property is not set, the getInstance() method creates a default class instance, org.apache.ws.security.components.crypto.BouncyCastle .如果提供程序属性没有设置,getInstance()方法创建一个默认的类的实例,org.apache.ws.security.components.crypto.BouncyCastle。
The provider is initialized to the values specified in the crypto.properties file found in the WSS4J .jar file.提供者是初始化为crypto.properties在指定的文件WSS4J的价值观中找到。jar文件。 As shipped, that file specifies org.apache.ws.security.components.crypto.Merlin as the provider class.作为发运,该文件指定类org.apache.ws.security.components.crypto.Merlin作为供应商。
private static final Crypto crypto = CryptoFactory.getInstance();
You use the AxisClient as the context engine for messaging operations.您使用作为消息引擎AxisClient行动范围内。
private AxisClient engine = null; private MessageContext msgContext = null; public WSSecuritySample() { engine = new AxisClient(new NullProvider()); msgContext = new MessageContext(engine); }
Creating the Target SOAP Envelope 创建目标SOAP信封
The following method creates and returns an Axis message from a SOAP envelope string.下面的方法创建并返回一个SOAP信封串一轴消息。
private Message getAxisMessage(String unsignedEnvelope) { InputStream inStream = new ByteArrayInputStream( unsignedEnvelope.getBytes()); Message axisMessage = new Message(inStream); axisMessage.setMessageContext(msgContext); return axisMessage; }
The SOAP envelope used in this article and passed to the getAxisMessage method shown above is illustrated as follows:在SOAP信封中使用的文章和方法传递给getAxisMessage如上所示如下:
<SOAP-ENV:Envelope xmlns:SOAP-ENV=http://www.w3.org/2003/05/soap-envelope xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <SOAP-ENV:Body> <sayHello xmlns= "http://jeffhanson.com/services/helloworld"> <value xmlns=""> Hello world! </value> </sayHello> </SOAP-ENV:Body> </SOAP-ENV:Envelope>
Signing a SOAP Message 签名SOAP消息
The following method uses the WSSignEnvelope class to sign a SOAP envelope and adds the signature data to the envelope in compliance with WS-Security.下面的方法使用WSSignEnvelope类签署一个SOAP信封,并增加了签名数据到与WS - Security的遵守信封。
public Message signSOAPEnvelope(SOAPEnvelope unsignedEnvelope) throws Exception { WSSignEnvelope signer = new WSSignEnvelope(); String alias = "16c73ab6-b892-458f-abf5-2f875f74882e"; String password = "security"; signer.setUserInfo(alias, password); Document doc = unsignedEnvelope.getAsDocument();
The "build" method creates the signed SOAP envelope. “建造”方法创建签署SOAP信封。 It takes a SOAP Envelope as a W3C Document and adds a WSS Signature header to it.它以一个W3C文档一个SOAP信封,并增加了一个WSS签名头到它。 The signed elements depend on the signature parts specified by the WSBaseMessage.setParts(java.util.Vector parts) method.已签署的内容取决于零件)方法java.util.Vector签字部分指定的WSBaseMessage.setParts(。 By default, it signs the SOAP Body element.默认情况下,它的SOAP Body元素的迹象。
The "crypto" parameter is the object that implements access to the keystore and handling of certificates.在“加密”参数是对象实现访问keystore和证书的处理。
WSS4J includes a default implementation, org.apache.ws.security.components.crypto.Merlin . WSS4J包含一个默认的实现,org.apache.ws.security.components.crypto.Merlin。
Document signedDoc = signer.build(doc, crypto); // Convert the signed document into a SOAP message. Message signedSOAPMsg = (org.apache.axis.Message)AxisUtil.toSOAPMessage(signedDoc); return signedSOAPMsg; }
Listing 1 shows a signed SOAP envelope as returned from the preceding method. 清单1显示了一个签名方法返回的SOAP信封,从前面的。
Adding Username Tokens to a SOAP Message 用户名添加到SOAP消息令牌
Listing 2 shows a WSS4J method that uses the WSEncryptBody class to add username tokens to a SOAP envelope in compliance with WS-Security. 清单2显示了一个WSS4J方法,使用WSEncryptBody类来添加用户名令牌到,安全的SOAP信封中的WS遵守。
The SOAP envelope contained within the Axis message returned from the method shown in Listing 2 will look similar to Listing 3 :在SOAP信封中包含的方法从内部消息显示返回轴清单2将类似于清单3 :
Encrypting SOAP Messages SOAP消息加密
The following method uses the WSEncryptBody class to encrypt part of a SOAP envelope in compliance with WS-Security.下面的方法使用WSEncryptBody类来加密一个与WS - Security的SOAP信封遵守的一部分。
public Message encryptSOAPEnvelope( SOAPEnvelope unsignedEnvelope, Message axisMessage) throws Exception { WSEncryptBody encrypt = new WSEncryptBody(); encrypt.setUserInfo( "16c73ab6-b892-458f-abf5-2f875f74882e"); // build the encrypted SOAP part Document doc = unsignedEnvelope.getAsDocument(); Document encryptedDoc = encrypt.build(doc, crypto); // Convert the document into a SOAP message Message encryptedMsg = (Message)AxisUtil.toSOAPMessage(encryptedDoc); // Retrieve the desired SOAP part String soapPart = encryptedMsg.getSOAPPartAsString(); ((SOAPPart)axisMessage.getSOAPPart()). setCurrentMessage(soapPart, SOAPPart.FORM_STRING); encryptedDoc = axisMessage.getSOAPEnvelope().getAsDocument(); // Convert the document into a SOAP message Message encryptedSOAPMsg = (Message)AxisUtil.toSOAPMessage(encryptedDoc); return encryptedSOAPMsg; }
The SOAP envelope contained within the Axis message returned from the preceding method will look like Listing 4 . SOAP信封从前面的方法中返回的消息将在轴样子清单4 。
The "main" Method “主”方法
Finally, a main method drives the methods defined above to sign, add username tokens to, and encrypt a SOAP envelope.最后,一个主要方法驱动签署上述定义的方法,添加的用户名令牌来,和加密SOAP信封。
public static void main(String[] args) { try { WSSecuritySample app = new WSSecuritySample(); Message axisMessage = app.getAxisMessage(soapMsg); SOAPEnvelope unsignedEnvelope = axisMessage.getSOAPEnvelope(); System.out.println( "<<< Unsigned and Unencrypted >>>"); XMLUtils.PrettyElementToWriter( unsignedEnvelope.getAsDOM(), new PrintWriter(System.out)); Message samlMsg = app.addUserTokens(unsignedEnvelope); System.out.println("\n<<< User Tokens >>>"); XMLUtils.PrettyElementToWriter( samlMsg.getSOAPEnvelope().getAsDOM(), new PrintWriter(System.out)); Message encryptedMsg = app.encryptSOAPEnvelope( unsignedEnvelope, axisMessage); System.out.println("\n<<< Encrypted >>>"); XMLUtils.PrettyElementToWriter( encryptedMsg.getSOAPEnvelope().getAsDOM(), new PrintWriter(System.out)); Message signedMsg = app.signSOAPEnvelope(unsignedEnvelope); System.out.println("\n<<< Signed >>>"); XMLUtils.PrettyElementToWriter( signedMsg.getSOAPEnvelope().getAsDOM(), new PrintWriter(System.out)); } catch (Exception e) { e.printStackTrace(); } }
Although the process may initially seem complex, a method such as the main method shown above simplifies the process considerably, breaking it down neatly into just a few steps: creating a SOAP envelope, and then signing, encrypting, and adding username tokens to it.虽然这个过程可能最初看起来复杂,上面的方法,例如显示为主要方法的过程大大简化,其分解成整齐的步骤只是几个例子:创建一个SOAP信封,然后签名,加密,并加入到它的用户名令牌。 I urge you to download the sample code for this article and experiment with the process.我敦促你下载的示例代码为这篇文章,并与实验过程。 The WSS4J framework provides the core methods you need to meet the WS-Security specifications.该WSS4J框架提供了您需要满足的WS - Security规范的核心方法。