01: package org.bouncycastle.jce.provider.test;
02:
03: import java.security.Key;
04: import java.security.KeyPair;
05: import java.security.KeyPairGenerator;
06: import java.security.MessageDigest;
07: import java.security.PrivateKey;
08: import java.security.PublicKey;
09: import java.security.SecureRandom;
10: import java.security.Security;
11:
12: import javax.crypto.Cipher;
13: import javax.crypto.KeyGenerator;
14:
15: import org.bouncycastle.jce.provider.BouncyCastleProvider;
16: import org.bouncycastle.util.test.SimpleTestResult;
17: import org.bouncycastle.util.test.Test;
18: import org.bouncycastle.util.test.TestResult;
19:
20: public class WrapTest implements Test {
21: public TestResult perform() {
22: try {
23: Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding",
24: "BC");
25: KeyPairGenerator fact = KeyPairGenerator.getInstance("RSA",
26: "BC");
27: fact.initialize(512, new SecureRandom());
28:
29: KeyPair keyPair = fact.generateKeyPair();
30:
31: PrivateKey priKey = keyPair.getPrivate();
32: PublicKey pubKey = keyPair.getPublic();
33:
34: KeyGenerator keyGen = KeyGenerator.getInstance("DES", "BC");
35: Key wrapKey = keyGen.generateKey();
36: cipher.init(Cipher.WRAP_MODE, wrapKey);
37: byte[] wrappedKey = cipher.wrap(priKey);
38:
39: cipher.init(Cipher.UNWRAP_MODE, wrapKey);
40: Key key = cipher.unwrap(wrappedKey, "RSA",
41: Cipher.PRIVATE_KEY);
42:
43: if (!MessageDigest.isEqual(priKey.getEncoded(), key
44: .getEncoded())) {
45: return new SimpleTestResult(false,
46: "Unwrapped key does not match");
47: }
48:
49: return new SimpleTestResult(true, getName() + ": Okay");
50: } catch (Exception e) {
51: return new SimpleTestResult(false, getName()
52: + ": exception - " + e.toString());
53: }
54: }
55:
56: public String getName() {
57: return "WrapTest";
58: }
59:
60: public static void main(String[] args) {
61: Security.addProvider(new BouncyCastleProvider());
62:
63: Test test = new WrapTest();
64: TestResult result = test.perform();
65:
66: System.out.println(result.toString());
67: }
68: }
|