KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > proactive > ext > security > ProActiveSecurity


1 /*
2 * ################################################################
3 *
4 * ProActive: The Java(TM) library for Parallel, Distributed,
5 * Concurrent computing with Security and Mobility
6 *
7 * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
8 * Contact: proactive-support@inria.fr
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
23 * USA
24 *
25 * Initial developer(s): The ProActive Team
26 * http://www.inria.fr/oasis/ProActive/contacts.html
27 * Contributor(s):
28 *
29 * ################################################################
30 */

31 package org.objectweb.proactive.ext.security;
32
33 import java.io.ByteArrayInputStream JavaDoc;
34 import java.math.BigInteger JavaDoc;
35 import java.security.InvalidKeyException JavaDoc;
36 import java.security.KeyPair JavaDoc;
37 import java.security.NoSuchProviderException JavaDoc;
38 import java.security.PrivateKey JavaDoc;
39 import java.security.Provider JavaDoc;
40 import java.security.PublicKey JavaDoc;
41 import java.security.SecureRandom JavaDoc;
42 import java.security.Security JavaDoc;
43 import java.security.SignatureException JavaDoc;
44 import java.security.cert.CertificateException JavaDoc;
45 import java.security.cert.CertificateFactory JavaDoc;
46 import java.security.cert.X509Certificate JavaDoc;
47 import java.sql.Date JavaDoc;
48 import java.text.DateFormat JavaDoc;
49 import java.util.ArrayList JavaDoc;
50 import java.util.Random JavaDoc;
51
52 import org.bouncycastle.asn1.ASN1EncodableVector;
53 import org.bouncycastle.asn1.ASN1Sequence;
54 import org.bouncycastle.asn1.DERInputStream;
55 import org.bouncycastle.asn1.DERSequence;
56 import org.bouncycastle.asn1.misc.MiscObjectIdentifiers;
57 import org.bouncycastle.asn1.misc.NetscapeCertType;
58 import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
59 import org.bouncycastle.asn1.x509.BasicConstraints;
60 import org.bouncycastle.asn1.x509.GeneralName;
61 import org.bouncycastle.asn1.x509.GeneralNames;
62 import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
63 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
64 import org.bouncycastle.asn1.x509.X509Extensions;
65 import org.bouncycastle.asn1.x509.X509Name;
66 import org.bouncycastle.jce.X509V3CertificateGenerator;
67 import org.bouncycastle.jce.provider.JDKKeyPairGenerator;
68 import org.objectweb.proactive.core.ProActiveException;
69 import org.objectweb.proactive.core.node.Node;
70 import org.objectweb.proactive.core.node.NodeFactory;
71 import org.objectweb.proactive.core.runtime.ProActiveRuntime;
72 import org.objectweb.proactive.core.runtime.RuntimeFactory;
73
74
75 public class ProActiveSecurity {
76     public static Object JavaDoc[] generateGenericCertificate() {
77         Provider JavaDoc myProvider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
78           Security.addProvider(myProvider);
79   
80
81         /* generation of a default certificate */
82         KeyPair JavaDoc keyPair = null;
83         SecureRandom JavaDoc rand = new SecureRandom JavaDoc();
84
85         JDKKeyPairGenerator.RSA keyPairGen = new JDKKeyPairGenerator.RSA();
86
87         keyPairGen.initialize(1024, rand);
88
89         keyPair = keyPairGen.generateKeyPair();
90
91         PrivateKey JavaDoc privateKey = keyPair.getPrivate();
92         PublicKey JavaDoc publicKey = keyPair.getPublic();
93         return generateCertificate("CN=Generic Certificate " +
94             new Random JavaDoc().nextLong() +
95             ", OU=Generic Certificate, EmailAddress=none", "CN=none", privateKey,
96             publicKey);
97     }
98
99     public static Object JavaDoc[] generateCertificate(String JavaDoc dnName,
100         String JavaDoc issuerName, PrivateKey JavaDoc caPrivKey, PublicKey JavaDoc caPubKey) {
101         KeyPair JavaDoc keyPair = null;
102         SecureRandom JavaDoc rand = new SecureRandom JavaDoc();
103
104         JDKKeyPairGenerator.RSA keyPairGen = new JDKKeyPairGenerator.RSA();
105
106         keyPairGen.initialize(1024, rand);
107
108         keyPair = keyPairGen.generateKeyPair();
109
110         PrivateKey JavaDoc privateKey = keyPair.getPrivate();
111         PublicKey JavaDoc publicKey = keyPair.getPublic();
112
113         X509V3CertificateGenerator certifGenerator = new X509V3CertificateGenerator();
114
115         X509Certificate JavaDoc certif = null;
116
117         DateFormat JavaDoc convert = DateFormat.getDateInstance();
118
119         certifGenerator.setPublicKey(publicKey);
120
121         String JavaDoc subjectCN = dnName;
122
123         // System.out.println("DefaultCertificate subjectCN " + subjectCN);
124
X509Name subject = new X509Name(subjectCN);
125         X509Name issuer = new X509Name(issuerName);
126
127         certifGenerator.setSubjectDN(subject);
128         certifGenerator.setIssuerDN(issuer);
129         certifGenerator.setSignatureAlgorithm("MD5withRSA");
130
131         Date JavaDoc start = new Date JavaDoc(System.currentTimeMillis() -
132                 (1000L * 60 * 60 * 24 * 30));
133         Date JavaDoc stop = new Date JavaDoc(System.currentTimeMillis() +
134                 (1000L * 60 * 60 * 24 * 30));
135
136         certifGenerator.setNotAfter(stop);
137         certifGenerator.setNotBefore(start);
138         certifGenerator.setPublicKey(publicKey);
139         certifGenerator.setSerialNumber(new BigInteger JavaDoc("1"));
140
141         certifGenerator.addExtension(X509Extensions.SubjectKeyIdentifier,
142             false, createSubjectKeyId(publicKey));
143
144         certifGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier,
145             false, createAuthorityKeyId(caPubKey, new X509Name(issuerName), 1));
146
147         certifGenerator.addExtension(X509Extensions.BasicConstraints, false,
148             new BasicConstraints(true));
149
150         certifGenerator.addExtension(MiscObjectIdentifiers.netscapeCertType,
151             false,
152             new NetscapeCertType(NetscapeCertType.smime |
153                 NetscapeCertType.sslServer));
154
155         try {
156             certif = certifGenerator.generateX509Certificate(privateKey, "BC");
157         } catch (InvalidKeyException JavaDoc e) {
158             e.printStackTrace();
159         } catch (NoSuchProviderException JavaDoc e) {
160             e.printStackTrace();
161         } catch (SecurityException JavaDoc e) {
162             e.printStackTrace();
163         } catch (SignatureException JavaDoc e) {
164             e.printStackTrace();
165         }
166
167         return new Object JavaDoc[] { certif, privateKey };
168     }
169
170     public static String JavaDoc retrieveVNName(Node node) {
171         if (NodeFactory.isNodeLocal(node)) {
172             // System.out.println("Launching OA nodeURL extracted locally: " + node.getVnName());
173
return node.getVnName();
174         }
175         String JavaDoc s = node.getNodeInformation().getName();
176
177         // int n = s.lastIndexOf("/");
178
// String name = s.substring(n + 1);
179
String JavaDoc vn = null;
180         try {
181             vn = RuntimeFactory.getDefaultRuntime().getVNName(node.getNodeInformation()
182                                                                   .getName());
183         } catch (ProActiveException e1) {
184             e1.printStackTrace();
185         }
186
187         // System.out.println("Launching OA nodeURL : " + s);
188
// System.out.println("Node url " + node.getNodeInformation().getURL());
189
// System.out.println("Launching OA nodeURL extracted: " + vn);
190
return vn;
191
192         /*int i = s.lastIndexOf("//");
193         String s2 = s.substring(i, s.length());
194         if (i > 0) {
195         System.out.println("coupeeeeeeee " + s2);
196         */

197
198         //vn = RuntimeFactory.getDefaultRuntime().getVNName(name);
199
}
200
201     //
202
// create the subject key identifier.
203
//
204
public static SubjectKeyIdentifier createSubjectKeyId(PublicKey JavaDoc pubKey) {
205         try {
206             ByteArrayInputStream JavaDoc bIn = new ByteArrayInputStream JavaDoc(pubKey.getEncoded());
207             SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(
208                         bIn).readObject());
209
210             return new SubjectKeyIdentifier(info);
211         } catch (Exception JavaDoc e) {
212             throw new RuntimeException JavaDoc("error creating key");
213         }
214     }
215
216     //
217
// create the authority key identifier.
218
//
219
public static AuthorityKeyIdentifier createAuthorityKeyId(
220         PublicKey JavaDoc pubKey, X509Name name, int sNumber) {
221         try {
222             ByteArrayInputStream JavaDoc bIn = new ByteArrayInputStream JavaDoc(pubKey.getEncoded());
223             SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(
224                         bIn).readObject());
225
226             GeneralName genName = new GeneralName(name);
227             ASN1EncodableVector v = new ASN1EncodableVector();
228
229                  v.add(genName);
230
231     
232             return new AuthorityKeyIdentifier(
233                 info, new GeneralNames(new DERSequence(v)), BigInteger.valueOf(sNumber));
234         } catch (Exception JavaDoc e) {
235             throw new RuntimeException JavaDoc("error creating AuthorityKeyId");
236         }
237     }
238
239     public static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey JavaDoc pubKey) {
240         try {
241             ByteArrayInputStream JavaDoc bIn = new ByteArrayInputStream JavaDoc(pubKey.getEncoded());
242             SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(
243                         bIn).readObject());
244
245             return new AuthorityKeyIdentifier(info);
246         } catch (Exception JavaDoc e) {
247             throw new RuntimeException JavaDoc("error creating AuthorityKeyId");
248         }
249     }
250
251     public static String JavaDoc retrieveVNName(String JavaDoc nodeName) {
252         String JavaDoc vn = null;
253         try {
254             vn = RuntimeFactory.getDefaultRuntime().getVNName(nodeName);
255         } catch (ProActiveException e1) {
256             e1.printStackTrace();
257         }
258
259         // System.out.println("Launching OA nodeURL : " + s);
260
// System.out.println("Node url " + node.getNodeInformation().getURL());
261
// System.out.println("Launching OA nodeURL extracted: " + vn);
262
return vn;
263
264         /*int i = s.lastIndexOf("//");
265         String s2 = s.substring(i, s.length());
266         if (i > 0) {
267         System.out.println("coupeeeeeeee " + s2);
268         */

269
270         //vn = RuntimeFactory.getDefaultRuntime().getVNName(name);
271
}
272
273     /**
274      * @param string
275      */

276     public static void migrateTo(PolicyServer ps, String JavaDoc bodyURL, Node nodeTo)
277         throws SecurityMigrationException {
278         PolicyServer runtimePolicyServer = null;
279         PolicyServer applicationPolicyServer = null;
280         String JavaDoc vnFrom;
281         String JavaDoc vn;
282         String JavaDoc vnTo;
283         vn = vnFrom = vnTo = null;
284         vnFrom = bodyURL;
285
286         ProActiveRuntime pr = null;
287
288         try {
289             runtimePolicyServer = RuntimeFactory.getDefaultRuntime()
290                                                 .getPolicyServer();
291
292             //applicationPolicyServer = RuntimeFactory.getDefaultRuntime().getPolicyServerFor()
293
//vnFrom = ProActive.getBodyOnThis().getNodeURL();
294
int n = vnFrom.lastIndexOf("/");
295             String JavaDoc name = vnFrom.substring(n + 1);
296
297             //System.out.println("name:" + name + " -- vnFrom :" + vnFrom);
298
vn = RuntimeFactory.getDefaultRuntime().getVNName(name);
299
300             vnTo = nodeTo.getVnName();
301             if (vnTo == null) {
302                 vnTo = nodeTo.getNodeInformation().getURL();
303                 n = vnTo.lastIndexOf("/");
304                 name = vnTo.substring(n + 1);
305                 // System.out.println("name:" + name + " -- vnTo :" + vnTo);
306
pr = nodeTo.getProActiveRuntime();
307                 vnTo = pr.getVNName(name);
308             }
309
310             // System.out.println("JE SUIS SUR " + vn + "ET je vais sur " + vnTo);
311
} catch (ProActiveException e1) {
312             e1.printStackTrace();
313         }
314
315         if (runtimePolicyServer != null) {
316             if (runtimePolicyServer.canMigrateTo("VN", vn, vnTo)) {
317             } else {
318                 throw new SecurityMigrationException("matching rule : VN[" +
319                     vn + "] --> VN[" + vnTo + "]");
320             }
321         }
322
323         if (ps != null) {
324             Communication runtimePolicy;
325             Communication VNPolicy;
326             Communication distantPolicy;
327
328             ArrayList JavaDoc arrayFrom = new ArrayList JavaDoc();
329             ArrayList JavaDoc arrayTo = new ArrayList JavaDoc();
330
331             if (vnFrom == null) {
332                 arrayFrom.add(new DefaultEntity());
333             } else {
334             // arrayFrom.add(new EntityVirtualNode(vnFrom));
335
}
336             if (vnTo == null) {
337                 arrayTo.add(new DefaultEntity());
338             } else {
339             // arrayTo.add(new EntityVirtualNode(vnTo));
340
}
341
342             SecurityContext sc = new SecurityContext(SecurityContext.MIGRATION_TO,
343                     arrayFrom, arrayTo);
344             try {
345                 sc = ps.getPolicy(sc);
346             } catch (SecurityNotAvailableException e) {
347                 // do nothing
348
}
349             if (sc.isMigration()) {
350             } else {
351                 throw new SecurityMigrationException("matching rule : VN[" +
352                     vn + "] --> VN[" + vnTo + "]");
353             }
354         }
355     }
356
357     public static X509Certificate JavaDoc decodeCertificate(byte[] encodedCert) {
358         X509Certificate JavaDoc certificate = null;
359
360         //
361
// Recover Servers Certificate
362
//
363
try {
364             CertificateFactory JavaDoc cf = CertificateFactory.getInstance("X.509");
365             certificate = (X509Certificate JavaDoc) cf.generateCertificate(new ByteArrayInputStream JavaDoc(
366                         encodedCert));
367         } catch (CertificateException JavaDoc e) {
368             e.printStackTrace();
369         }
370         return certificate;
371     }
372 }
373
Popular Tags