aboutsummaryrefslogtreecommitdiffstats
path: root/libraries/spongycastle/mail/src/main/java/org/spongycastle/mail/smime/examples/ExampleUtils.java
blob: 10c0f06c298eca3813bb18391f53bd8f47242b33 (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
77
package org.bouncycastle.mail.smime.examples;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.util.Enumeration;

import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;

public class ExampleUtils
{
    /**
     * Dump the content of the passed in BodyPart to the file fileName.
     *
     * @throws MessagingException
     * @throws IOException
     */
    public static void dumpContent(
        MimeBodyPart bodyPart, 
        String fileName) 
        throws MessagingException, IOException
    {
        //
        // print mime type of compressed content
        //
        System.out.println("content type: " + bodyPart.getContentType());
        
        //
        // recover the compressed content
        //
        OutputStream out = new FileOutputStream(fileName);
        InputStream in = bodyPart.getInputStream();
        
        byte[] buf = new byte[10000];
        int    len;
        
        while ((len = in.read(buf, 0, buf.length)) > 0)
        {
            out.write(buf, 0, len);
        }
        
        out.close();
    }
    
    public static String findKeyAlias(
        KeyStore store, 
        String storeName, 
        char[] password) 
        throws Exception
    {
        store.load(new FileInputStream(storeName), password);
    
        Enumeration e = store.aliases();
        String      keyAlias = null;
    
        while (e.hasMoreElements())
        {
            String  alias = (String)e.nextElement();
    
            if (store.isKeyEntry(alias))
            {
                keyAlias = alias;
            }
        }
    
        if (keyAlias == null)
        {
            throw new IllegalArgumentException("can't find a private key in keyStore: " + storeName);
        }
        
        return keyAlias;
    }
}