01: package org.bouncycastle.jce.provider.test;
02:
03: import java.security.Key;
04: import java.security.SecureRandom;
05: import java.security.Security;
06:
07: import javax.crypto.Cipher;
08: import javax.crypto.KeyGenerator;
09: import javax.crypto.spec.IvParameterSpec;
10:
11: import org.bouncycastle.jce.provider.BouncyCastleProvider;
12: import org.bouncycastle.util.test.SimpleTest;
13:
14: public class SlotTwoTest extends SimpleTest {
15: byte[] plainData = "abcdefghijklmnopqrstuvwxyz".getBytes();
16:
17: public String getName() {
18: return "SlotTwo";
19: }
20:
21: public void performTest() throws Exception {
22: Security.removeProvider("BC");
23: Security.insertProviderAt(new BouncyCastleProvider(), 2);
24:
25: KeyGenerator keyGen = KeyGenerator.getInstance("DESede", "BC");
26:
27: keyGen.init(new SecureRandom());
28:
29: Key key = keyGen.generateKey();
30:
31: testDesEde(key, "ECB", "PKCS7Padding");
32: testDesEde(key, "CBC", "PKCS7Padding");
33: testDesEde(key, "CTR", "NoPadding");
34: testDesEde(key, "CTR", "PKCS7Padding");
35: testDesEde(key, "OFB", "PKCS7Padding");
36: testDesEde(key, "CFB", "PKCS7Padding");
37:
38: Security.removeProvider("BC");
39: Security.addProvider(new BouncyCastleProvider());
40: }
41:
42: private void testDesEde(Key key, String mode, String padding)
43: throws Exception {
44: Cipher encrypt = Cipher.getInstance("DESede/" + mode + "/"
45: + padding, "BC");
46: Cipher decrypt = Cipher.getInstance("DESede/" + mode + "/"
47: + padding);
48:
49: if (!decrypt.getProvider().getName().equals("BC")) {
50: fail("BC provider not returned for DESede/" + mode + "/"
51: + padding + " got "
52: + decrypt.getProvider().getName());
53: }
54:
55: encrypt.init(Cipher.ENCRYPT_MODE, key);
56:
57: byte[] encryptedBytes = encrypt.doFinal(plainData);
58: byte[] ivBytes = encrypt.getIV();
59:
60: if (ivBytes != null) {
61: IvParameterSpec ivp = new IvParameterSpec(ivBytes);
62:
63: decrypt.init(Cipher.DECRYPT_MODE, key, ivp);
64: } else {
65: decrypt.init(Cipher.DECRYPT_MODE, key);
66: }
67:
68: byte[] plainBytes = decrypt.doFinal(encryptedBytes, 0,
69: encryptedBytes.length);
70:
71: if (!areEqual(plainData, plainBytes)) {
72: fail("decryption test failed.");
73: }
74: }
75:
76: public static void main(String[] args) {
77: runTest(new SlotTwoTest());
78: }
79: }
|