-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetInstance.java
More file actions
63 lines (53 loc) · 2.22 KB
/
NetInstance.java
File metadata and controls
63 lines (53 loc) · 2.22 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
package com.github.redreaperlp.socketapi.ns;
import com.github.redreaperlp.socketapi.communication.Connection;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public interface NetInstance {
void notifyConnectionClosed(Connection con);
byte[] encryptionKey();
void setEncryptionKey(byte[] key);
default void useEncryption(String key) {
try {
byte[] keyHash = MessageDigest.getInstance("SHA-256").digest(key.getBytes());
setEncryptionKey(keyHash);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
default boolean usesEncrytion() {
return encryptionKey() != null;
}
default String encrypt(String plaintext) {
try {
SecretKeySpec secretKey = new SecretKeySpec(encryptionKey(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException |
InvalidKeyException e) {
throw new RuntimeException(e);
}
}
default String decrypt(String ciphertext) {
try {
SecretKeySpec secretKey = new SecretKeySpec(encryptionKey(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
return new String(decryptedBytes);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException |
InvalidKeyException e) {
throw new RuntimeException(e);
}
}
void stop();
boolean stopped();
}