Skip to content

Commit a1a80fe

Browse files
author
kevin.w.wall
committed
Example showing how to persist encrypted data in a file stored in the file system.
This is a slightly enhanced version that is shown in the User Guide.
1 parent 7f6fe25 commit a1a80fe

1 file changed

Lines changed: 173 additions & 0 deletions

File tree

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
import java.io.*;
2+
import org.owasp.esapi.*;
3+
import org.owasp.esapi.crypto.*;
4+
import org.owasp.esapi.errors.*;
5+
import org.owasp.esapi.codecs.*;
6+
7+
/** A slightly more complex example showing encoding encrypted data and writing
8+
* it out to a file. This is very similar to the example in the ESAPI User
9+
* Guide for "Symmetric Encryption in ESAPI 2.0".
10+
*/
11+
public class PersistedEncryptedData
12+
{
13+
public enum OutputEncoding { raw, base64, hex }
14+
15+
private static final OutputEncoding dfltEncoding = OutputEncoding.raw;
16+
17+
private static boolean useBase64(OutputEncoding encoding) {
18+
if ( encoding.equals(OutputEncoding.base64) ) {
19+
return true;
20+
} else {
21+
return false;
22+
}
23+
}
24+
25+
private static boolean useHex(OutputEncoding encoding) {
26+
if ( encoding.equals(OutputEncoding.hex) ) {
27+
return true;
28+
} else {
29+
return false;
30+
}
31+
}
32+
33+
/** Take the specified plaintext, encrypt it, and then persist it
34+
* to the specified file name according to the specified encoding.
35+
*
36+
* @param plaintext The {@code PlainText} we wish to encrypt.
37+
* @param filemane Name of the file in which to store the encrypted, encoded data.
38+
* @param encoding How it was encoded. Either base64, hex, or raw (meaning
39+
* no encoding was used).
40+
* @returns
41+
* @throws EncryptionException
42+
* @throws IOException
43+
* @throws UnsupportedEncodingException
44+
*/
45+
public static int persistEncryptedData(PlainText plaintext,
46+
String filename,
47+
OutputEncoding encoding)
48+
throws EncryptionException, IOException, UnsupportedEncodingException
49+
{
50+
File serializedFile = new File(filename);
51+
serializedFile.delete(); // Delete any old serialized file.
52+
53+
CipherText ct = ESAPI.encryptor().encrypt(plaintext);
54+
byte[] serializedCiphertext = ct.asPortableSerializedByteArray();
55+
String encodedStr = null;
56+
byte[] serializedBytes = null;
57+
58+
if ( useBase64(encoding) ) {
59+
encodedStr = Base64.encodeBytes(serializedCiphertext);
60+
serializedBytes = encodedStr.getBytes("UTF-8");
61+
} else if ( useHex(encoding) ) {
62+
encodedStr = Hex.encode(serializedCiphertext, true);
63+
serializedBytes = encodedStr.getBytes("UTF-8");
64+
} else {
65+
serializedBytes = serializedCiphertext;
66+
}
67+
68+
FileOutputStream fos = new FileOutputStream(serializedFile);
69+
fos.write( serializedBytes );
70+
fos.close();
71+
return serializedBytes.length;
72+
}
73+
74+
/** Read the specified file name containing encoded encrypted data,
75+
* and then decode it and decrypt it to retrieve the original plaintext.
76+
*
77+
* @param encryptedDataFilename Name of the file to read containing the
78+
* encoded, encrypted data.
79+
* @param encoding How it was encoded. Either base64, hex, or raw (meaning
80+
* no encoding was used).
81+
* @returns The original {@code PlainText} object.
82+
* @throws EncryptionException
83+
* @throws IOException
84+
* @throws UnsupportedEncodingException
85+
*/
86+
public static PlainText restorePlaintext(String encryptedDataFilename,
87+
OutputEncoding encoding)
88+
throws EncryptionException, IOException, UnsupportedEncodingException
89+
{
90+
File serializedFile = new File(encryptedDataFilename);
91+
FileInputStream fis = new FileInputStream(serializedFile);
92+
int avail = fis.available();
93+
byte[] bytes = new byte[avail];
94+
fis.read(bytes, 0, avail);
95+
String encodedEncryptedData = new String(bytes, "UTF-8");
96+
97+
byte[] serializedCiphertext;
98+
99+
if ( useBase64(encoding) ) {
100+
serializedCiphertext = Base64.decode(encodedEncryptedData);
101+
} else if ( useHex(encoding) ) {
102+
serializedCiphertext = Hex.decode(encodedEncryptedData);
103+
} else {
104+
// Raw encoding
105+
serializedCiphertext = bytes;
106+
}
107+
System.out.println("Serialized ciphertext is " + serializedCiphertext.length +
108+
" bytes.");
109+
110+
CipherText restoredCipherText =
111+
CipherText.fromPortableSerializedBytes(serializedCiphertext);
112+
fis.close();
113+
PlainText plaintext = ESAPI.encryptor().decrypt(restoredCipherText);
114+
return plaintext;
115+
}
116+
117+
/**
118+
* Usage: PersistedEncryptedData plaintext filename [{raw|base64|hex}]
119+
*/
120+
public static void main(String[] args) {
121+
122+
try {
123+
String plaintext = null;
124+
String filename = null;
125+
OutputEncoding encoding = dfltEncoding;
126+
127+
if ( args.length >= 3 ) {
128+
plaintext = args[0];
129+
filename = args[1];
130+
if ( args[2].equalsIgnoreCase("raw") ) {
131+
encoding = OutputEncoding.raw;
132+
} else if ( args[2].equalsIgnoreCase("base64") ) {
133+
encoding = OutputEncoding.base64;
134+
} else if ( args[2].equalsIgnoreCase("hex") ) {
135+
encoding = OutputEncoding.hex;
136+
} else {
137+
System.err.println(args[2] + ": Unrecognized encoding; using default.");
138+
encoding = dfltEncoding;
139+
}
140+
} else {
141+
System.err.println("Usage: PersistedEncryptedData plaintext " +
142+
"filename [{raw|base64|hex}]");
143+
System.exit(2);
144+
}
145+
146+
// Add file suffix, appropriate to encoding
147+
filename = filename + "." + encoding;
148+
149+
System.out.println("Encrypting " + plaintext.length() +
150+
" bytes of plaintext and storing in file '" +
151+
filename + "'.");
152+
153+
int n = PersistedEncryptedData.persistEncryptedData(
154+
new PlainText(plaintext),
155+
filename, encoding);
156+
157+
System.out.println("Wrote " + n + " bytes to encrypted file " + filename + ".");
158+
File f = new File(filename);
159+
PlainText pt = PersistedEncryptedData.restorePlaintext(filename, encoding);
160+
161+
System.out.println("Plaintext recovered from encrypted file was: " + pt);
162+
if ( pt.toString().equals( plaintext ) ) {
163+
System.out.println("Plaintext recovered successfully.");
164+
} else {
165+
System.out.println("Recovered plaintext differs from original plaintext.");
166+
}
167+
} catch(Throwable t) {
168+
System.err.println("Caught: " + t.getClass().getName() +
169+
"; exception msg: " + t);
170+
t.printStackTrace(System.err);
171+
}
172+
}
173+
}

0 commit comments

Comments
 (0)