· 7 years ago · Dec 18, 2018, 10:14 AM
1package crypto;
2
3
4import sample.Controller;
5
6import javax.crypto.Cipher;
7import javax.crypto.CipherOutputStream;
8import javax.crypto.SecretKey;
9import java.io.FileInputStream;
10import java.io.FileOutputStream;
11import java.security.*;
12
13public class Server {
14 private PublicKey publicKey;
15
16 private PrivateKey privateKey;
17
18 private SecretKey secretKey;
19
20 private String algorithm;
21
22 private byte[] data;
23
24 private Util util;
25
26 private Controller controller;
27
28
29 public Server() {
30 this.util = new Util();
31 }
32
33 // Создаёт пару открытый/закрытый ключ
34 public void generateKeyPair() throws Exception {
35 System.out.println(("generating a key pair"));
36 controller.addTextToTextArea("generating a key pair");
37 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
38 kpg.initialize(512, new SecureRandom());
39 KeyPair keyPair = kpg.generateKeyPair();
40 publicKey = keyPair.getPublic();
41 privateKey = keyPair.getPrivate();
42 }
43
44 // ÐкÑпортирует открытый ключ
45 public void exportPublicKey() throws Exception {
46 System.out.println("exporting the public key");
47 controller.addTextToTextArea("exporting the public key");
48 try (FileOutputStream fos = new FileOutputStream("publicKey.txt", false)) {
49 fos.write(publicKey.getEncoded());
50 }
51 }
52
53 // Импортирует и раÑшифровывает Ñимметричные ключи, Ñгенерированные клиентом
54 public void importSymKeys(String algorithm) throws Exception {
55 this.algorithm = algorithm;
56 System.out.println(("importing and decrypting the sym keys"));
57 controller.addTextToTextArea("importing and decrypting the sym keys");
58 Cipher cipher = Cipher.getInstance("RSA");
59 byte[] encryptedSymKey;
60 try (FileInputStream fis = new FileInputStream("symKey.txt")) {
61 encryptedSymKey = new byte[fis.available()];
62 fis.read(encryptedSymKey);
63 }
64 cipher.init(Cipher.UNWRAP_MODE, privateKey);
65 this.secretKey = (SecretKey) cipher.unwrap(encryptedSymKey, algorithm,
66 Cipher.SECRET_KEY);
67 }
68
69 // Зашифровывает данные при помощи Ñимметричных ключей, полученных от клиента,
70// поÑле чего ÑкÑпортирует зашифрованные данные
71 public void encryptData() throws Exception {
72 System.out.println(("encrypting data with the sym keys"));
73 controller.addTextToTextArea("encrypting data with the sym keys");
74 Cipher cipher = Cipher.getInstance(this.algorithm);
75 cipher.init(Cipher.ENCRYPT_MODE, this.secretKey);
76 try (CipherOutputStream cos = new CipherOutputStream(new
77 FileOutputStream("encodedData.txt", false), cipher)) {
78 cos.write(data);
79 }
80 }
81
82 // ПодпиÑывает данные ÐЦП, Ñформированной на оÑнове закрытого ключа, поÑле
83// чего ÑкÑпортирует Ñформированные ÐЦП
84 public void signData() throws Exception {
85 System.out.println(("signing the data"));
86 controller.addTextToTextArea("signing the data");
87 Signature signature = Signature.getInstance("MD5withRSA");
88 signature.initSign(this.privateKey);
89 signature.update(this.data);
90 try (FileOutputStream fos = new FileOutputStream("signature.txt", false)) {
91 fos.write(signature.sign());
92 }
93 }
94
95 public void initAndDecodeData(String dataType, String value) {
96 switch (dataType) {
97 case "char":
98 char res = 0;
99 for (int i = 0; i < value.length(); i++) {
100 res += value.charAt(i);
101 }
102 data = util.charToBytes(res);
103 break;
104 case "String":
105 data = util.stringToByte((value));
106 break;
107 case "boolean":
108 data = util.booleanToByte(Boolean.parseBoolean(value));
109 break;
110 case "int":
111 data = util.intToBytes(Integer.parseInt(value));
112 break;
113 case "short":
114 data = util.shortToBytes(Short.parseShort(value));
115 break;
116 case "long":
117 data = util.longToBytes(Long.parseLong(value));
118 break;
119 case "float":
120 data = util.floatToByte(Float.parseFloat(value));
121 break;
122 case "byte":
123 data = util.convertByte(Byte.parseByte(value));
124 break;
125 case "double":
126 data = util.doubleToByte(Double.parseDouble(value));
127 break;
128 }
129 }
130
131 public void setController(Controller controller) {
132 this.controller = controller;
133 }
134}