KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > jcetaglib > lib > Asymmetric


1 /*
2   Name: Asymmetric.java
3   Licensing: LGPL
4
5   API: Sun (http://java.sun.com) JCE 1.2.2 API (cleanroom implementation by Bouncy Castle)
6   Provider: Bouncy Castle (http://www.bouncycastle.org)
7
8   Disclaimer:
9
10   COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND,
11   EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE
12   IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE
13   RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE
14   PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR)
15   ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY
16   CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED
17   HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
18
19   (C) Copyright 2003 Gert Van Ham
20 */

21
22 package net.sourceforge.jcetaglib.lib;
23
24 import net.sourceforge.jcetaglib.exceptions.CryptoException;
25 import org.bouncycastle.jce.provider.BouncyCastleProvider;
26 import org.bouncycastle.util.encoders.Base64;
27
28 import javax.crypto.Cipher;
29 import java.io.*;
30 import java.security.PrivateKey JavaDoc;
31 import java.security.PublicKey JavaDoc;
32 import java.security.Security JavaDoc;
33
34 /**
35  * Asymmetric encryption & decryption routines with BouncyCastle JCE provider
36  *
37  * @author Gert Van Ham
38  * @author hamgert@users.sourceforge.net
39  * @author http://jcetaglib.sourceforge.net
40  * @version $Id: Asymmetric.java,v 1.3 2004/04/15 07:28:24 hamgert Exp $
41  */

42 public class Asymmetric {
43     // buffersizes in bytes
44
private static int BUFFERSIZE_TEXT = 64;
45
46     /**
47      * Encrypts text with a public RSA key (from a X.509 certificate)
48      *
49      * @param text the text to encrypt
50      * @param encryptKey the public encryption key
51      * @return the encrypted text in BASE64 format
52      * @throws CryptoException for encryption errors
53      */

54     public static StringBuffer JavaDoc encrypt(StringBuffer JavaDoc text
55                                        , PublicKey JavaDoc encryptKey)
56             throws CryptoException {
57
58         ByteArrayOutputStream bao = null;
59         DataOutputStream dao = null;
60
61         try {
62             bao = new ByteArrayOutputStream();
63             dao = new DataOutputStream(bao);
64
65             // Encrypt
66
encrypt(new ByteArrayInputStream(text.toString().getBytes()), dao, encryptKey, BUFFERSIZE_TEXT);
67
68             return new StringBuffer JavaDoc(new String JavaDoc(Base64.encode(bao.toByteArray())));
69         } catch (IOException ioe) {
70             ioe.printStackTrace();
71             throw new CryptoException(ioe.getMessage());
72         } finally {
73             if (dao != null) {
74                 // close outputstream
75
try {
76                     dao.close();
77                 } catch (IOException e) {
78                     ;
79                 }
80             }
81         }
82     }
83
84     /**
85      * Encrypts an inputstream with a public RSA key (from a X.509 certificate)
86      * This result can only be decrypted with the corresponding private key
87      *
88      * @param is the inputstream to encrypt
89      * @param daos returns ciphered outputstream
90      * @param encryptKey the public encryption key
91      * @throws IOException I/O errors
92      * @throws CryptoException for all encryption errors
93      **/

94     public static void encrypt(InputStream is
95                                , DataOutputStream daos
96                                , PublicKey JavaDoc encryptKey
97                                , int bufferlength)
98             throws CryptoException, IOException {
99
100         Cipher cipher = null;
101
102         try {
103             Security.addProvider(new BouncyCastleProvider());
104
105             // create a cipher object: ("algorithm/mode/padding", provider)
106
cipher = Cipher.getInstance("RSA/ECB/OAEPPadding", "BC");
107
108             cipher.init(Cipher.ENCRYPT_MODE, encryptKey);
109
110             byte[] buffer = new byte[bufferlength];
111             int length = 0;
112             while ((length = is.read(buffer)) != -1) {
113                 cipher.update(buffer, 0, length);
114             }
115
116             byte[] result = cipher.doFinal();
117             daos.write(result);
118         } catch (IOException ioe) {
119             ioe.printStackTrace();
120             throw new IOException(ioe.getMessage());
121         } catch (Exception JavaDoc ex) {
122             ex.printStackTrace();
123             throw new CryptoException(ex.getMessage());
124         }
125     }
126
127     /**
128      * decrypts text with a private RSA key (from a X.509 certificate)
129      *
130      * @param text the text to decrypt
131      * @param decryptKey the private key
132      * @return the encrypted text in BASE64 format
133      * @throws CryptoException for encryption errors
134      */

135     public static StringBuffer JavaDoc decrypt(StringBuffer JavaDoc text
136                                        , PrivateKey JavaDoc decryptKey)
137             throws CryptoException {
138
139         ByteArrayOutputStream bao = null;
140         DataOutputStream dao = null;
141
142         try {
143             bao = new ByteArrayOutputStream();
144             dao = new DataOutputStream(bao);
145
146             // Decrypt
147
decrypt(new ByteArrayInputStream(Base64.decode(text.toString())), dao, decryptKey, BUFFERSIZE_TEXT);
148
149             return new StringBuffer JavaDoc(new String JavaDoc(bao.toByteArray()));
150         } catch (IOException ioe) {
151             ioe.printStackTrace();
152             throw new CryptoException(ioe.getMessage());
153         } finally {
154             if (dao != null) {
155                 // close outputstream
156
try {
157                     dao.close();
158                 } catch (IOException e) {
159                     ;
160                 }
161             }
162         }
163     }
164
165     /**
166      * Decrypts an inputstream, encrypted with an RSA public key (from X.509), with the
167      * corresponding private key
168      *
169      * @param is the inputstream to decrypt
170      * @param daos returns deciphered outputstream
171      * @param decryptKey the private key
172      * @throws IOException I/O errors
173      * @throws CryptoException for all encryption errors
174      **/

175     public static void decrypt(InputStream is
176                                , DataOutputStream daos
177                                , PrivateKey JavaDoc decryptKey
178                                , int bufferlength)
179             throws CryptoException, IOException {
180
181         Cipher cipher = null;
182
183         try {
184             Security.addProvider(new BouncyCastleProvider());
185
186             // create a cipher object: ("algorithm/mode/padding", provider)
187
cipher = Cipher.getInstance("RSA/ECB/OAEPPadding", "BC");
188
189             cipher.init(Cipher.DECRYPT_MODE, decryptKey);
190
191             byte[] buffer = new byte[bufferlength];
192             int length = 0;
193             while ((length = is.read(buffer)) != -1) {
194                 cipher.update(buffer, 0, length);
195             }
196
197             byte[] result = cipher.doFinal();
198             daos.write(result);
199         } catch (IOException ioe) {
200             ioe.printStackTrace();
201             throw new IOException(ioe.getMessage());
202         } catch (Exception JavaDoc ex) {
203             ex.printStackTrace();
204             throw new CryptoException(ex.getMessage());
205         }
206     }
207 }
208
Popular Tags