View Javadoc
1   package civitas.crypto.signature;
2   
3   import static org.junit.jupiter.api.Assertions.assertEquals;
4   import static org.junit.jupiter.api.Assertions.assertThrows;
5   import static org.mockito.Mockito.verify;
6   
7   import java.security.InvalidKeyException;
8   import java.security.SignatureException;
9   
10  import org.bouncycastle.crypto.CryptoException;
11  import org.junit.jupiter.api.DisplayName;
12  import org.junit.jupiter.api.Test;
13  import org.mockito.InjectMocks;
14  
15  import civitas.common.RandomAwareTestBase;
16  import civitas.crypto.rsapublickey.PublicKeyTestData;
17  import civitas.util.BasicValuesTestData;
18  
19  class SignWithPublicKeyTest extends RandomAwareTestBase
20  		implements PublicKeyTestData, SignatureTestData, BasicValuesTestData {
21  
22  	@InjectMocks
23  	SignWithPublicKey signWithPublicKey;
24  
25  	@Test
26  	@DisplayName(
27  			"""
28  			signs with public key
29  			- initializes the rsa signer with the private key
30  			- updates the rsa signer with the byte array to sign
31  			- obtains the signature using the rsa signer
32  			- converts the public key to string
33  			- returns the signature containing the signature and the string version of the public key
34  			""")
35  	void test() throws CryptoException, InvalidKeyException, SignatureException {
36  		assertEquals(
37  				SIGNATURE_OF_AUTH_NONCE_WITH_KEY,
38  				signWithPublicKey.apply(PRIVATE_KEY, PUBLIC_KEY, AUTHENTICATION_NONCE.getBytes()));
39  		verify(signWithPublicKey.convertPublicKeyToString).apply(PUBLIC_KEY);
40  		verify(signWithPublicKey.cryptoBase.rsaSigner).initSign(PRIVATE_KEY);
41  		verify(signWithPublicKey.cryptoBase.rsaSigner).update(AUTHENTICATION_NONCE.getBytes());
42  	}
43  
44  	@Test
45  	@DisplayName("when the private key is bad, a CryptoException is thrown\n")
46  	void test2() {
47  		assertThrows(
48  				CryptoException.class,
49  				() -> signWithPublicKey.apply(PRIVATE_KEY_BAD, PUBLIC_KEY, AUTHENTICATION_NONCE.getBytes()));
50  	}
51  
52  	@Test
53  	@DisplayName(
54  			"""
55  			when signing a string, sings the hash of the string
56  			- computes the hash of the string
57  			- initializes the rsa signer with the private key
58  			- updates the rsa signer with the hash
59  			- obtains the signature using the rsa signer
60  			- converts the public key to string
61  			- returns the signature containing the signature and the string version of the public key
62  			""")
63  	void test1() throws CryptoException, InvalidKeyException, SignatureException {
64  		assertEquals(SIGNATURE_OF_AUTH_NONCE_WITH_KEY, signWithPublicKey.apply(PRIVATE_KEY, PUBLIC_KEY, SOMESTRING));
65  		verify(signWithPublicKey.cryptoHash).apply(SOMESTRING.getBytes());
66  		verify(signWithPublicKey.convertPublicKeyToString).apply(PUBLIC_KEY);
67  		verify(signWithPublicKey.cryptoBase.rsaSigner).initSign(PRIVATE_KEY);
68  		verify(signWithPublicKey.cryptoBase.rsaSigner).update(SOMESTRING_HASH);
69  	}
70  }