summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/encryption/AsymEncryptionHandler.java
blob: 8c074cadb82a17ab40cbac5697ad5fc0f17d6147 (plain) (blame)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
package org.openslx.encryption;

import java.security.InvalidKeyException;
import java.security.InvalidParameterException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class AsymEncryptionHandler
{
	private static final Logger LOG = LogManager.getLogger( AsymEncryptionHandler.class );

	private final Key key;

	/**
	 * Create a handler.
	 */
	public AsymEncryptionHandler( Key key )
	{
		this.key = key;
	}

	/**
	 * Encrypt given plain text message with the key this class was
	 * instantiated with.
	 * 
	 * @param cleartext a clear text message
	 * @return The encrypted message
	 */
	public byte[] encryptMessage( byte[] cleartext )
	{
		try {
			Cipher cipher = Cipher.getInstance( "RSA" );
			cipher.init( Cipher.ENCRYPT_MODE, key );
			return cipher.doFinal( cleartext );
		} catch ( NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e ) {
			LOG.warn( "Cannot encrypt message", e );
		}
		return null;
	}

	/**
	 * Verify an encrypted message, where we know the plain text.
	 * 
	 * @param encryptedMessage
	 * @param expectedCleartext
	 * @return true if the message matches the expected plain text after decrypting
	 */
	public boolean verifyMessage( byte[] encryptedMessage, byte[] expectedCleartext )
	{
		try {
			Cipher cipher = Cipher.getInstance( "RSA" );
			cipher.init( Cipher.DECRYPT_MODE, key );
			byte[] result = cipher.doFinal( encryptedMessage );
			return Arrays.equals( expectedCleartext, result );
		} catch ( NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e ) {
			LOG.warn( "Cannot verify message", e );
		}
		return false;
	}

	/**
	 * Generate a fresh RSA key pair.
	 * 
	 * @param bits length of key
	 * @return key pair, or null on error
	 */
	public static KeyPair generateKeyPair( int bits )
	{
		try {
			KeyPairGenerator kpg = KeyPairGenerator.getInstance( "RSA" );
			kpg.initialize( bits );
			return kpg.genKeyPair();
		} catch ( NoSuchAlgorithmException | InvalidParameterException e ) {
			LOG.warn( "Cannot generate RSA Keypair", e );
			return null;
		}
	}

}