summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/imagemaster/util/AsymMessageSign.java
blob: 134b399aabee0fc5daefcf7b75fa2954df598b75 (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
package org.openslx.imagemaster.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;

public class AsymMessageSign
{
	
	KeyPair pair;
	
//	String alias = "ftp";
//	String password = "password";
//	String file = "./config/keystore.jks";
	
	
	public AsymMessageSign(String alias, String password, String file) throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException, UnrecoverableKeyException
	{
		KeyStore keystore = KeyStore.getInstance( "JKS" );
		keystore.load( new FileInputStream( new File( file ) ), password.toCharArray() );
		Certificate cert = null;

		Key key = keystore.getKey( alias,
				password.toCharArray() );

		if ( key instanceof PrivateKey ) {
			cert = keystore.getCertificate( alias );
			PublicKey publicKey = cert.getPublicKey();
			pair = new KeyPair( publicKey, (PrivateKey)key );
		}
	}

	public byte[] signMessage( String message ) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException
	{
		Signature signature = Signature.getInstance( "SHA256WITHRSA" );
		signature.initSign( pair.getPrivate() );
		signature.update( message.getBytes() );
		return signature.sign();
	}

	public boolean verifyMessage( byte[] signedMessage, byte[] realMessage ) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException
	{
		Signature signature = Signature.getInstance( "SHA256WITHRSA" );
		signature.initVerify( pair.getPublic() );
		signature.update( realMessage );
		return signature.verify( signedMessage );
	}

}