-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.java
More file actions
67 lines (54 loc) · 2.63 KB
/
Utils.java
File metadata and controls
67 lines (54 loc) · 2.63 KB
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
import javax.crypto.*;
import java.security.*;
public class Utils {
public KeyGenerator keyGen;
public Cipher cipher;
public Signature sig;
public Utils() throws NoSuchAlgorithmException, NoSuchPaddingException {
this.keyGen = KeyGenerator.getInstance("AES");
this.keyGen.init(128);
this.cipher = Cipher.getInstance("AES"); // Transformation of the algorithm
this.sig = Signature.getInstance("SHA256withRSA");
}
public SecretKey generateKey() throws NoSuchAlgorithmException {
return this.keyGen.generateKey();
}
public byte[] encryptMessage(byte[] plainBytes, SecretKey key) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
this.cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherBytes = this.cipher.doFinal(plainBytes);
return cipherBytes;
}
public String decryptMessage(byte[] cipherBytes, SecretKey key) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
this.cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainBytes = this.cipher.doFinal(cipherBytes);
return new String(plainBytes);
}
public KeyPair kPGGen(int keysize) throws NoSuchAlgorithmException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(keysize);
KeyPair kp = kpg.genKeyPair();
return kp;
}
public byte[] wrapKey(SecretKey symmetric, PublicKey publicKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException {
Cipher cipher1 = Cipher.getInstance("RSA");
cipher1.init(Cipher.WRAP_MODE, publicKey);
byte[] wrapped = cipher1.wrap(symmetric);
return wrapped;
}
public SecretKey unwrapKey(byte[] symmetric, PrivateKey privateKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
Cipher cipher1 = Cipher.getInstance("RSA");
cipher1.init(Cipher.UNWRAP_MODE, privateKey);
SecretKey wrapped = (SecretKey) cipher1.unwrap(symmetric,"AES", Cipher.SECRET_KEY);
return wrapped;
}
public byte[] signMessage(byte[] message, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
sig.initSign(privateKey, new SecureRandom());
sig.update(message);
return sig.sign();
}
public boolean verifySign(byte[] signatureBytes, byte[] messageBytes, PublicKey publicKey) throws InvalidKeyException, SignatureException {
sig.initVerify(publicKey);
sig.update(messageBytes);
return sig.verify(signatureBytes);
}
}