-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleCryptoMisuse.java
More file actions
65 lines (56 loc) · 2.36 KB
/
Copy pathSimpleCryptoMisuse.java
File metadata and controls
65 lines (56 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.KeyFactory;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Random;
import java.util.List;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class SimpleCryptoMisuse {
public static void main(String... args) throws Exception {
Setup.setup();
var in = new BufferedReader(new StringReader("test\nwith\nmultiple\nlines"));
var keygen = KeyGenerator.getInstance("AES");
keygen.init(256);
var key = keygen.generateKey();
misuse(in, key);
}
private static List<byte[]> misuse(BufferedReader dataStream, Key key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
String line;
List<byte[]> encryptedData = new java.util.ArrayList<byte[]>();
while ((line = dataStream.readLine()) != null) {
cipher.init(Cipher.ENCRYPT_MODE, key);
encryptedData.add(cipher.doFinal(line.getBytes("utf-8")));
}
return encryptedData;
}
private static class Setup {
public static void setup() {
// Enforce the usage of the (regular or verified) BouncyCastle JCA implementation by removing the one
// included in the JDK.
for (final Provider provider : Security.getProviders()) {
Security.removeProvider(provider.getName());
}
Security.addProvider(new BouncyCastleProvider());
try {
Class.forName("BouncyCastle.bc.VerifiedRandom");
Security.addProvider(new VerifiedRandomProvider());
Security.setProperty("securerandom.strongAlgorithms", "VerifiedSecureRandom");
} catch (ClassNotFoundException e) {
// Verified random does not exist - just don't use it then
}
}
private static class VerifiedRandomProvider extends Provider {
protected VerifiedRandomProvider() {
super("VerifiedRandomProvider", "1.0.0", "Use a verified SecureRandom instance");
put("SecureRandom.VerifiedSecureRandom", "BouncyCastle.bc.VerifiedRandom");
}
}
}
}