Advertisement
Guest User

Untitled

a guest
Jul 28th, 2013
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.25 KB | None | 0 0
  1. makecert.exe -r -n "CN=rootCA,O=Organization,OU=Org Unit,L=Location,S=SH,C=Country" -pe -ss root -sr LocalMachine -sky exchange -m 96 -a sha1 -len 2048 rootCA.cer -sv rootCA.pvk
  2. makecert.exe -n "CN=serverCA" -pe -ss my -sr LocalMachine -sky exchange -m 96 -in "rootCA" -is root -ir LocalMachine -a sha1 -eku 1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2 serverCA.cer
  3. makecert.exe -n "CN=clientCA" -pe -ss my -sr CurrentUser -sky exchange -m 96 -in "rootCA" -is root -ir LocalMachine -a sha1 -eku 1.3.6.1.5.5.7.3.2 clientCA.cer -sv clientCA.
  4. pvk2pfx.exe -pvk clientCA.pvk -spc clientCA.cer -pfx clientCA.pfx
  5.  
  6. <?xml version="1.0"?>
  7. <configuration>
  8. <system.serviceModel>
  9. <extensions>
  10. <behaviorExtensions>
  11. <add name="consoleOutputBehavior" type="JsonTestService.ConsoleOutputBehaviorExtensionElement, JsonTestService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
  12. </behaviorExtensions>
  13. </extensions>
  14. <standardEndpoints>
  15. <webHttpEndpoint>
  16. <standardEndpoint name="JsonStandardEndpoint" defaultOutgoingResponseFormat="Json"
  17. automaticFormatSelectionEnabled="true">
  18. <security mode="Transport">
  19. <transport clientCredentialType="Certificate" proxyCredentialType="None" realm="" />
  20. </security>
  21. </standardEndpoint>
  22. </webHttpEndpoint>
  23. </standardEndpoints>
  24. <bindings>
  25. <webHttpBinding>
  26. <binding name="JsonBinding">
  27. <security mode="Transport">
  28. <transport clientCredentialType="Certificate" proxyCredentialType="None" realm="" />
  29. </security>
  30. </binding>
  31. </webHttpBinding>
  32. </bindings>
  33. <serviceHostingEnvironment aspNetCompatibilityEnabled="false" />
  34. <behaviors>
  35. <endpointBehaviors>
  36. <behavior name="jsonBehavior">
  37. <webHttp defaultBodyStyle="Wrapped" defaultOutgoingResponseFormat="Json" />
  38. </behavior>
  39. </endpointBehaviors>
  40. <serviceBehaviors>
  41. <behavior name="defaultBehavior">
  42. <serviceDebug includeExceptionDetailInFaults="true" />
  43. <serviceCredentials>
  44. <clientCertificate>
  45. <authentication certificateValidationMode="Custom" mapClientCertificateToWindowsAccount="false"
  46. customCertificateValidatorType="JsonTestService.CustomX509CertificateValidator, JsonTestService"
  47. />
  48. </clientCertificate>
  49. <serviceCertificate findValue="serverCA" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
  50. </serviceCredentials>
  51. </behavior>
  52. </serviceBehaviors>
  53. </behaviors>
  54. <services>
  55. <service behaviorConfiguration="defaultBehavior" name="JsonTestService.TestService">
  56. <endpoint address="json" behaviorConfiguration="jsonBehavior"
  57. binding="webHttpBinding" bindingConfiguration="JsonBinding"
  58. name="JsonEndpoint" contract="JsonTestService.ITestService" kind="webHttpEndpoint"
  59. endpointConfiguration="JsonStandardEndpoint">
  60. </endpoint>
  61. </service>
  62. </services>
  63. </system.serviceModel>
  64. <system.web>
  65. <authentication mode="None" />
  66. </system.web>
  67. </configuration>
  68.  
  69. namespace JsonTestService{
  70. ///
  71. /// DataContract
  72. ///
  73. [DataContract(Name = "Foo", Namespace = "http://www.example.com/data")]
  74. public class FooDataContract
  75. {
  76. [DataMember(Order = 0)]
  77. public string Item { get; set; }
  78. [DataMember(Order = 1)]
  79. public int Count { get; set; }
  80. }
  81.  
  82. ///
  83. /// Service Contract
  84. ///
  85. [ServiceContract(Namespace = "http://www.example.com/service")]
  86. public interface ITestService
  87. {
  88. [OperationContract]
  89. [WebInvoke(Method = "POST"
  90. , ResponseFormat = WebMessageFormat.Json
  91. , RequestFormat = WebMessageFormat.Json
  92. , BodyStyle = WebMessageBodyStyle.WrappedRequest
  93. , UriTemplate = "GetFoo.json/{name}?item={item}&count={countOfFoo}")]
  94. FooDataContract[] GetFoo(string name, int item, int countOfFoo);
  95.  
  96. [OperationContract]
  97. [WebInvoke(Method = "GET"
  98. , ResponseFormat = WebMessageFormat.Json
  99. , RequestFormat = WebMessageFormat.Json
  100. , BodyStyle = WebMessageBodyStyle.WrappedRequest
  101. , UriTemplate = "GetFooRaw.json")]
  102. FooDataContract[] GetFooRaw();
  103. }
  104.  
  105. ///
  106. /// Service Implementation
  107. ///
  108. ///
  109. /// Each request will have its own instance of the service
  110. ///
  111. [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
  112. public class TestService : ITestService
  113. {
  114. public FooDataContract[] GetFoo(string name, int item, int countOfFoo)
  115. {
  116. List result = null;
  117. for (int i = 0; i ();
  118. result.Add(new FooDataContract()
  119. {
  120. // default to "null"
  121. Name = (name ?? "null") + "_" + i,
  122. Age = age
  123. });
  124. }
  125. return result == null ? null : result.ToArray();
  126. }
  127. public FooDataContract[] GetFooRaw()
  128. {
  129. List result = new List();
  130. for (int i = 0; i < 5; i++)
  131. result.Add(new FooDataContract() { Item = (i + 1) * 6, Name = "Test" + i.ToString() });
  132. return result.ToArray();
  133. }
  134. }
  135.  
  136. private void testSSLDataTransfer() throws ClientProtocolException, IOException, Exception
  137. {
  138. try {
  139. SchemeRegistry schemeRegistry = new SchemeRegistry();
  140. schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  141. schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(getKeyStore(),"",getTrustStore()), 443)); //password is empty
  142.  
  143. HttpParams params = new BasicHttpParams();
  144. params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
  145. params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
  146. params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
  147. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  148. HttpProtocolParams.setContentCharset(params, "utf8");
  149.  
  150. ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
  151. HttpContext context = new BasicHttpContext();
  152. DefaultHttpClient client = new DefaultHttpClient(clientConnectionManager, params);
  153.  
  154. HttpPost post = new HttpPost("https://10.12.14.16:443/JsonTest/TestService.svc/json/GetFoo.json/Test?item=12&count=2");
  155. HttpGet get = new HttpGet("https://10.12.14.16:443/JsonTest/TestService.svc/json/GetFooBar.json");
  156. post.setHeader("Accept", "application/json");
  157. post.setHeader("Content-type", "application/json");
  158. post.setHeader("User-Agent", "android");
  159. get.setHeader("Accept", "application/json");
  160. get.setHeader("Content-type", "application/json");
  161. get.setHeader("User-Agent", "android");
  162.  
  163. HttpResponse response = client.execute(get, context);
  164. String statusLine = response.getStatusLine().toString(); //for debuf to see the response
  165. HttpEntity responseEntity = response.getEntity();
  166. InputStream stream = responseEntity.getContent();
  167. InputStreamReader reader = new InputStreamReader(stream);
  168.  
  169. java.lang.StringBuffer stringBuffer = new java.lang.StringBuffer();
  170. int read = 0;
  171. while((read = reader.read()) >= 0)
  172. stringBuffer.append((char)read);
  173.  
  174. String s = stringBuffer.toString();
  175. stream.close();
  176. } catch (ClientProtocolException e) {
  177. throw e;
  178. } catch (IOException e) {
  179. String text = e.getMessage();
  180. throw e;
  181. } catch (Exception e) {
  182. throw e;
  183. }
  184. }
  185.  
  186. private KeyStore getKeyStore() throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableKeyException, Exception
  187. {
  188. KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
  189. InputStream in = this.getApplicationContext().getResources().openRawResource(R.raw.keystore);
  190. try {
  191. keystore.load(in, "changeit".toCharArray());
  192. Key key = keystore.getKey("client", null); //It has no password and this way it finds the Key
  193. }
  194. catch (Exception e) {
  195. throw e;
  196. } finally {
  197. in.close();
  198. }
  199. return keystore;
  200. }
  201.  
  202. private KeyStore getTrustStore() throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException
  203. {
  204. KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
  205. InputStream in = this.getApplicationContext().getResources().openRawResource(R.raw.truststore);
  206. try {
  207. truststore.load(in, "changeit".toCharArray());
  208. } finally {
  209. in.close();
  210. }
  211. return truststore;
  212. }
  213.  
  214. import java.io.IOException;
  215. import java.net.InetAddress;
  216. import java.net.InetSocketAddress;
  217. import java.net.Socket;
  218. import java.net.UnknownHostException;
  219. import java.security.KeyStore;
  220.  
  221. import javax.net.ssl.KeyManager;
  222. import javax.net.ssl.KeyManagerFactory;
  223. import javax.net.ssl.SSLContext;
  224. import javax.net.ssl.SSLSocket;
  225. import javax.net.ssl.TrustManager;
  226.  
  227. import org.apache.http.conn.ConnectTimeoutException;
  228. import org.apache.http.conn.scheme.LayeredSocketFactory;
  229. import org.apache.http.conn.scheme.SocketFactory;
  230. import org.apache.http.params.HttpConnectionParams;
  231. import org.apache.http.params.HttpParams;
  232.  
  233. /*
  234. * Licensed to the Apache Software Foundation (ASF) under one
  235. * or more contributor license agreements. See the NOTICE file
  236. * distributed with this work for additional information
  237. * regarding copyright ownership. The ASF licenses this file
  238. * to you under the Apache License, Version 2.0 (the
  239. * "License"); you may not use this file except in compliance
  240. * with the License. You may obtain a copy of the License at
  241. *
  242. * http://www.apache.org/licenses/LICENSE-2.0
  243. *
  244. * Unless required by applicable law or agreed to in writing,
  245. * software distributed under the License is distributed on an
  246. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  247. * KIND, either express or implied. See the License for the
  248. * specific language governing permissions and limitations
  249. * under the License.
  250. */
  251.  
  252.  
  253. /**
  254. * This socket factory will create ssl socket that accepts self signed
  255. * certificate
  256. *
  257. * @author olamy
  258. * @version $Id: EasySSLSocketFactory.java 765355 2009-04-15 20:59:07Z evenisse
  259. * $
  260. * @since 1.2.3
  261. */
  262. public class EasySSLSocketFactory implements SocketFactory, LayeredSocketFactory {
  263.  
  264. private SSLContext sslcontext = null;
  265. private KeyStore keystore = null;
  266. private KeyStore truststore = null;
  267. String keystorepassword = null;
  268.  
  269. public EasySSLSocketFactory()
  270. {
  271. }
  272.  
  273. public EasySSLSocketFactory(KeyStore keystore, String keystorepassword,KeyStore truststore)
  274. {
  275. this.keystore = keystore;
  276. this.keystorepassword = keystorepassword;
  277. this.truststore = truststore;
  278. }
  279.  
  280. private static SSLContext createEasySSLContext(KeyStore keystore, String keystorepassword,KeyStore truststore) throws IOException {
  281. try {
  282.  
  283. KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  284. keyManagerFactory.init(keystore, keystorepassword.toCharArray());
  285. KeyManager[] list = keyManagerFactory.getKeyManagers();
  286.  
  287. SSLContext context = SSLContext.getInstance("TLS");
  288. context.init(list, new TrustManager[] { new EasyX509TrustManager(truststore) }, null);
  289. return context;
  290. } catch (Exception e) {
  291. throw new IOException(e.getMessage());
  292. }
  293. }
  294.  
  295. private SSLContext getSSLContext() throws IOException {
  296. if (this.sslcontext == null) {
  297. this.sslcontext = createEasySSLContext(keystore, keystorepassword, truststore);
  298. }
  299. return this.sslcontext;
  300. }
  301.  
  302. /**
  303. * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
  304. * java.lang.String, int, java.net.InetAddress, int,
  305. * org.apache.http.params.HttpParams)
  306. */
  307. public Socket connectSocket(Socket sock, String host, int port,
  308. InetAddress localAddress, int localPort, HttpParams params)
  309. throws IOException, UnknownHostException, ConnectTimeoutException {
  310. int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
  311. int soTimeout = HttpConnectionParams.getSoTimeout(params);
  312.  
  313. InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
  314. SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
  315.  
  316. if ((localAddress != null) || (localPort > 0)) {
  317. // we need to bind explicitly
  318. if (localPort < 0) {
  319. localPort = 0; // indicates "any"
  320. }
  321. InetSocketAddress isa = new InetSocketAddress(localAddress,
  322. localPort);
  323. sslsock.bind(isa);
  324. }
  325.  
  326. sslsock.connect(remoteAddress, connTimeout);
  327. sslsock.setSoTimeout(soTimeout);
  328. return sslsock;
  329. }
  330.  
  331. /**
  332. * @see org.apache.http.conn.scheme.SocketFactory#createSocket()
  333. */
  334. public Socket createSocket() throws IOException {
  335. return getSSLContext().getSocketFactory().createSocket();
  336. }
  337.  
  338. /**
  339. * @see org.apache.http.conn.scheme.SocketFactory#isSecure(java.net.Socket)
  340. */
  341. public boolean isSecure(Socket socket) throws IllegalArgumentException {
  342. return true;
  343. }
  344.  
  345. /**
  346. * @see org.apache.http.conn.scheme.LayeredSocketFactory#createSocket(java.net.Socket,
  347. * java.lang.String, int, boolean)
  348. */
  349. public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
  350. return getSSLContext().getSocketFactory().createSocket(socket, host, port,autoClose);
  351. }
  352.  
  353. // -------------------------------------------------------------------
  354. // javadoc in org.apache.http.conn.scheme.SocketFactory says :
  355. // Both Object.equals() and Object.hashCode() must be overridden
  356. // for the correct operation of some connection managers
  357. // -------------------------------------------------------------------
  358.  
  359. public boolean equals(Object obj) {
  360. return ((obj != null) && obj.getClass().equals(EasySSLSocketFactory.class));
  361. }
  362.  
  363. public int hashCode() {
  364. return EasySSLSocketFactory.class.hashCode();
  365. }
  366. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement