· 7 years ago · Jun 24, 2018, 07:26 PM
1public class PacketDecoader extends ByteToMessageDecoder {
2
3
4@Getter
5@Setter
6private Decryption mode = Decryption.NONE;
7@Getter
8@Setter
9private SecretKey AESKey;
10
11@Override
12protected synchronized void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
13 PacketSerializer packetSerializer = null;
14 System.out.println("Starting decoader for packet");
15 if(mode == Decryption.AES) {
16 packetSerializer = new
17PacketSerializer(EncryptionUtills.dycryptWithAES(AESKey, msg));
18 }
19 if(mode == Decryption.NONE) {
20 packetSerializer = new PacketSerializer(msg);
21 }
22 long timestamp = packetSerializer.readVarLong();
23 System.out.println("TimeStamp " + timestamp);
24 if(System.currentTimeMillis() - timestamp > 2000) {
25 System.out.println("Warnig recived packet that was over 2 seconds to late");
26 return;
27 }
28 int id = packetSerializer.readVarInt();
29 System.out.println("Packet id " + id);
30 Class<? extends Packet> packetclass = NettyClient.getInstance().getPacketRegistry().getClassByID(id);
31 if(packetclass == null) {
32 System.out.println("No class found for packet with id " + id);
33 return;
34 }
35 Packet packet = packetclass.newInstance();
36 packet.Read(packetSerializer);
37 if(packetSerializer.getBuf().readableBytes() > 0) {
38 System.out.println("Having " + packetSerializer.readableBytes() +" more bytes then red!");
39 }
40 out.add(packet);
41
42
43}
44
45public enum Decryption{
46 AES,
47 NONE;
48}
49
50public class PacketEncoader extends MessageToByteEncoder<Packet>{
51@Getter
52@Setter
53private Encryption mode = Encryption.NONE;
54@Getter
55@Setter
56private SecretKey AESKey;
57@Override
58protected void encode(ChannelHandlerContext ctx, Packet msg, ByteBuf out) throws Exception {
59 int id = NettyServer.getInstance().getPacketRegistry().getIdForPacket(msg);
60 if(id == -1) {
61 System.out.println(Main.pr + "No id for packet " + msg.getClass().getName());
62 return;
63 }
64 PacketSerializer packetSerializer = new PacketSerializer(out.alloc().buffer());
65 packetSerializer.writeVarLong(System.currentTimeMillis());
66 packetSerializer.writeVarInt(id);
67 msg.Write(packetSerializer);
68 if(mode == Encryption.AES) {
69 out.writeBytes(EncryptionUtills.encryptWithAES(AESKey, packetSerializer.getBuf()));
70 }
71 if(mode == Encryption.NONE) {
72 out.writeBytes(packetSerializer.getBuf());
73 }
74 System.out.println("Encoded packet " + msg.getClass().getSimpleName() + " with size " + packetSerializer.writerIndex());
75}
76
77public enum Encryption{
78AES,
79NONE;
80}
81
82public class EncryptionUtills {
83
84
85
86public static ByteBuf decryptWithRSA(ByteBuf encrypted, PrivateKey mykey) throws Exception {
87 Cipher cipher = Cipher.getInstance("RSA");
88 cipher.init(Cipher.DECRYPT_MODE, mykey);
89 return wrightbytes(encrypted.alloc().buffer(), cipher.doFinal(readbytes(encrypted)));
90}
91
92public static ByteBuf encryptWithRSA(ByteBuf encrypted, PublicKey mykey) throws Exception {
93 Cipher cipher = Cipher.getInstance("RSA");
94 cipher.init(Cipher.ENCRYPT_MODE, mykey);
95 return wrightbytes(encrypted.alloc().buffer(), cipher.doFinal(readbytes(encrypted)));
96}
97
98
99
100
101
102
103public static ByteBuf encryptWithAES(SecretKey key, ByteBuf message) throws Exception {
104 Cipher cipher = Cipher.getInstance("AES");
105 cipher.init(Cipher.ENCRYPT_MODE, key);
106 return wrightbytes(message.alloc().buffer(), cipher.doFinal(readbytes(message)));
107}
108
109public static ByteBuf dycryptWithAES(SecretKey key, ByteBuf message) throws Exception {
110 Cipher cipher = Cipher.getInstance("AES");
111 cipher.init(Cipher.DECRYPT_MODE, key);
112 return wrightbytes(message.alloc().buffer(), cipher.doFinal(readbytes(message)));
113}
114
115public static boolean isKeyPairValid(String filename) {
116 File file = new File(Main.instance.getDataFolder(), filename + ".key");
117 File file2 = new File(Main.instance.getDataFolder(), filename + ".pub");
118 return file.exists() && file2.exists();
119}
120
121public static KeyPair generateSSLKeyPair(int size, String outfile) throws Exception{
122 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
123 kpg.initialize(size);
124 KeyPair kp = kpg.generateKeyPair();
125 Key pub = kp.getPublic();
126 Key pvt = kp.getPrivate();
127 Base64.Encoder encoder = Base64.getEncoder();
128
129 Writer out = new FileWriter(new File(Main.instance.getDataFolder(), outfile + ".key"));
130 out.write("-----BEGIN RSA PRIVATE KEY-----n");
131 out.write(encoder.encodeToString(pvt.getEncoded()));
132 out.write("n-----END RSA PRIVATE KEY-----n");
133 out.close();
134
135 out = new FileWriter(new File(Main.instance.getDataFolder(), outfile + ".pub"));
136 out.write("-----BEGIN RSA PUBLIC KEY-----n");
137 out.write(encoder.encodeToString(pub.getEncoded()));
138 out.write("n-----END RSA PUBLIC KEY-----n");
139 out.close();
140 return kp;
141}
142
143
144public static KeyPair readKeys(File keys) throws Exception {
145 Base64.Decoder decoder = Base64.getDecoder();
146 Path path = Paths.get(keys + ".key");
147 List<String> lines = Files.readAllLines(path);
148 byte[] bytes = decoder.decode(lines.get(1));
149
150 /* Generate private key. */
151 PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes);
152 KeyFactory kf = KeyFactory.getInstance("RSA");
153 PrivateKey pvt = kf.generatePrivate(ks);
154
155 Path path2 = Paths.get(keys + ".pub");
156 List<String> lines2 = Files.readAllLines(path2);
157 byte[] bytes2 = decoder.decode(lines2.get(1));
158
159 /* Generate public key. */
160 X509EncodedKeySpec ks2 = new X509EncodedKeySpec(bytes2);
161 KeyFactory kf2 = KeyFactory.getInstance("RSA");
162 PublicKey pub = kf2.generatePublic(ks2);
163 return new KeyPair(pub, pvt);
164}
165
166public static SecretKey generateAESKey(int size) throws NoSuchAlgorithmException {
167 KeyGenerator kgen = KeyGenerator.getInstance("AES");
168 kgen.init(size);
169 return kgen.generateKey();
170}
171
172private static ByteBuf wrightbytes(ByteBuf wright, byte[] data) {
173 int i = 0;
174 while (i < data.length) {
175 wright.writeByte(data[i]);
176 i++;
177 }
178 return wright;
179}
180private static byte[] readbytes(ByteBuf buf) {
181 int k = buf.readableBytes();
182 byte[] data = new byte[k];
183 int i = 0;
184 while (i < k) {
185 data[i] = buf.readByte();
186 i++;
187 }
188 return data;
189}
190
191 // The higher the number of iterations the more
192 // expensive computing the hash is for us and
193 // also for an attacker.
194 private static final int iterations = 20*1000;
195 private static final int saltLen = 32;
196 private static final int desiredKeyLen = 256;
197
198 /** Computes a salted PBKDF2 hash of given plaintext password
199 suitable for storing in a database.
200 Empty passwords are not supported. */
201 public static String getSaltedHash(String password) throws Exception {
202 byte[] salt = SecureRandom.getInstance("SHA1PRNG").generateSeed(saltLen);
203 // store the salt with the password
204 return org.apache.commons.codec.binary.Base64.encodeBase64String(salt) + "$" + hash(password, salt);
205 }
206
207 /** Checks whether given plaintext password corresponds
208 to a stored salted hash of the password. */
209 public static boolean check(String password, String stored) throws Exception{
210 String[] saltAndPass = stored.split("\$");
211 if (saltAndPass.length != 2) {
212 throw new IllegalStateException(
213 "The stored password have the form 'salt$hash'");
214 }
215 String hashOfInput = hash(password, org.apache.commons.codec.binary.Base64.decodeBase64(saltAndPass[0]));
216 return hashOfInput.equals(saltAndPass[1]);
217 }
218
219 // using PBKDF2 from Sun, an alternative is https://github.com/wg/scrypt
220 // cf. http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html
221 private static String hash(String password, byte[] salt) throws Exception {
222 if (password == null || password.length() == 0)
223 throw new IllegalArgumentException("Empty passwords are not supported.");
224 SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
225 SecretKey key = f.generateSecret(new PBEKeySpec(
226 password.toCharArray(), salt, iterations, desiredKeyLen)
227 );
228 return org.apache.commons.codec.binary.Base64.encodeBase64String(key.getEncoded());
229 }
230
231}