KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > util > Base64


1 /*************************************************************************
2  * *
3  * EJBCA: The OpenSource Certificate Authority *
4  * *
5  * This software is free software; you can redistribute it and/or *
6  * modify it under the terms of the GNU Lesser General Public *
7  * License as published by the Free Software Foundation; either *
8  * version 2.1 of the License, or any later version. *
9  * *
10  * See terms of license at gnu.org. *
11  * *
12  *************************************************************************/

13  
14 package org.ejbca.util;
15
16 import java.io.ByteArrayOutputStream JavaDoc;
17
18
19 /**
20  * This class implements a BASE64 Character encoder/decoder as specified in RFC1521.
21  * It extends the bouncycastle implementation and adds the functionality to split lines
22  * with a '\n' after every 64 bytes.
23  *
24  * @version $Id: Base64.java,v 1.1 2006/01/17 20:32:19 anatom Exp $
25  */

26 public class Base64 {
27
28     /**
29      * encode the input data producong a base 64 encoded byte array with the output lines be split by '\n' (64 byte rows).
30      *
31      * @param data data to be encoded
32      * @return a byte array containing the base 64 encoded data.
33      */

34     public static byte[] encode(byte[] data) {
35         return encode(data, true);
36     }
37
38     /**
39      * encode the input data producong a base 64 encoded byte array.
40      *
41      * @param data the data to be encoded
42      * @param splitlines whether the output lines will be split by '\n' (64 byte rows) or not.
43      * @return a byte array containing the base 64 encoded data.
44      */

45     public static byte[] encode(byte[] data, boolean splitlines) {
46         byte[] bytes = org.bouncycastle.util.encoders.Base64.encode(data);
47         if (!splitlines) {
48             return bytes;
49         }
50
51         // make sure we get limited lines...
52
ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc();
53         for (int i = 0; i < bytes.length; i += 64) {
54             if ((i + 64) < bytes.length) {
55                 os.write(bytes, i, 64);
56                 os.write('\n');
57             } else {
58                 os.write(bytes, i, bytes.length - i);
59             }
60         }
61         return os.toByteArray();
62     }
63     
64     public static byte[] decode(byte[] bytes) {
65         return org.bouncycastle.util.encoders.Base64.decode(bytes);
66     }
67
68 }
69
Popular Tags