aboutsummaryrefslogtreecommitdiffstats
path: root/libraries/spongycastle/prov/src/test/java/org/spongycastle/jce/provider/test/WrapTest.java
blob: 5cf112441f00b16e8dea5a102baa3168509e4955 (plain)
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
66
67
68
69
70
71
72
73
74
75
76
package org.spongycastle.jce.provider.test;

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.spongycastle.util.test.SimpleTestResult;
import org.spongycastle.util.test.Test;
import org.spongycastle.util.test.TestResult;

public class WrapTest
    implements Test
{
    public TestResult perform()
    {
        try
        {
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding", "SC");
            KeyPairGenerator fact = KeyPairGenerator.getInstance("RSA", "SC");
            fact.initialize(512, new SecureRandom());

            KeyPair keyPair = fact.generateKeyPair();

            PrivateKey  priKey = keyPair.getPrivate();
            PublicKey   pubKey = keyPair.getPublic();

            KeyGenerator keyGen = KeyGenerator.getInstance("DES", "SC");
            Key wrapKey = keyGen.generateKey();
            cipher.init(Cipher.WRAP_MODE, wrapKey);
            byte[] wrappedKey = cipher.wrap(priKey);

            cipher.init(Cipher.UNWRAP_MODE, wrapKey);
            Key key = cipher.unwrap(wrappedKey, "RSA", Cipher.PRIVATE_KEY);

            if (!MessageDigest.isEqual(priKey.getEncoded(), key.getEncoded()))
            {
                return new SimpleTestResult(false, "Unwrapped key does not match");
            }

            return new SimpleTestResult(true, getName() + ": Okay");
        }
        catch (Exception e)
        {
            return new SimpleTestResult(false, getName() + ": exception - " + e.toString(), e);
        }
    }

    public String getName()
    {
        return "WrapTest";
    }

    public static void main(
        String[]    args)
    {
        Security.addProvider(new BouncyCastleProvider());

        Test            test = new WrapTest();
        TestResult      result = test.perform();

        System.out.println(result.toString());
        if (result.getException() != null)
        {
            result.getException().printStackTrace();
        }
    }
}