-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
352 lines (290 loc) · 8.35 KB
/
main.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package main
// spark v3
// version 20231213
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
)
const (
// 根据 RSA 分组
chunkSizeEncode = 245 // 加密分块大小,根据密钥长度调整
chunkSizeDecode = 256 // 解密分块大小
)
func main() {
genCmd := flag.NewFlagSet("gen", flag.ExitOnError)
genKeyName := genCmd.String("k", "key", "key name")
signCmd := flag.NewFlagSet("sign", flag.ExitOnError)
signFileNames := signCmd.String("f", "", "file names (separated by space)")
signKeyName := signCmd.String("k", "key", "key name")
signOutput := signCmd.String("o", "ok.sgn", "output file name")
verifyCmd := flag.NewFlagSet("verify", flag.ExitOnError)
verifyFileNames := verifyCmd.String("f", "", "file names (separated by space)")
verifySignature := verifyCmd.String("s", "ok.sgn", "signature file name")
verifyKeyName := verifyCmd.String("k", "key", "key name")
encodeCmd := flag.NewFlagSet("encode", flag.ExitOnError)
encodeFileName := encodeCmd.String("f", "", "file name")
encodeKeyName := encodeCmd.String("k", "key", "key name")
encodeOutputFile := encodeCmd.String("o", "encrypted", "output file name")
decodeCmd := flag.NewFlagSet("decode", flag.ExitOnError)
decodeFileName := decodeCmd.String("f", "", "file name")
decodeKeyName := decodeCmd.String("k", "key", "key name")
decodeOutputFile := decodeCmd.String("o", "decrypted", "output file name")
if len(os.Args) < 2 {
fmt.Println("--------------------------------------------------------")
fmt.Println("Usage: spark.exe [command]")
fmt.Println("Available commands: gen, sign, verify, encode, decode.")
fmt.Println("This Project was created as a demo for XDU's 'Spark Cup', 2023.")
fmt.Println("Using Golang, it support Windows, Linux, and other systems.")
fmt.Println("Spark version 3 added support for encode and decode. ")
fmt.Println("For more information, please turn to Instruction.md")
fmt.Println("--------------------------------------------------------")
return
}
switch os.Args[1] {
case "gen":
genCmd.Parse(os.Args[2:])
generateKeyPair(*genKeyName)
case "sign":
signCmd.Parse(os.Args[2:])
signFiles(*signFileNames, *signKeyName, *signOutput)
case "verify":
verifyCmd.Parse(os.Args[2:])
verifySignatureFiles(*verifyFileNames, *verifySignature, *verifyKeyName)
case "encode":
encodeCmd.Parse(os.Args[2:])
encodeFile(*encodeFileName, *encodeKeyName, *encodeOutputFile)
case "decode":
decodeCmd.Parse(os.Args[2:])
decodeFile(*decodeFileName, *decodeKeyName, *decodeOutputFile)
default:
fmt.Println("Unknown command:", os.Args[1])
}
}
func generateKeyPair(keyName string) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println("Failed to generate key pair:", err)
return
}
publicKey := &privateKey.PublicKey
privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
privateKeyPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: privateKeyBytes,
})
err = os.WriteFile(keyName+".scrkey", privateKeyPEM, 0600)
if err != nil {
fmt.Println("Failed to save private key:", err)
return
}
publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
fmt.Println("Failed to marshal public key:", err)
return
}
publicKeyPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: publicKeyBytes,
})
err = os.WriteFile(keyName+".pub", publicKeyPEM, 0644)
if err != nil {
fmt.Println("Failed to save public key:", err)
return
}
fmt.Println("Key pair generated successfully.")
}
func signFiles(fileNames, keyName, outputName string) {
privateKeyPEM, err := os.ReadFile(keyName + ".scrkey")
if err != nil {
fmt.Println("Failed to read private key:", err)
return
}
block, _ := pem.Decode(privateKeyPEM)
if block == nil || block.Type != "RSA PRIVATE KEY" {
fmt.Println("Invalid private key")
return
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
fmt.Println("Failed to parse private key:", err)
return
}
files := strings.Split(fileNames, " ")
if len(files) == 0 {
fmt.Println("No files specified")
return
}
fileData := make([]byte, 0)
for _, fileName := range files {
data, err := os.ReadFile(fileName)
if err != nil {
fmt.Println("Failed to read file:", err)
return
}
fileData = append(fileData, data...)
}
hash := sha256.Sum256(fileData)
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hash[:])
if err != nil {
fmt.Println("Failed to sign file:", err)
return
}
signatureBase64 := base64.StdEncoding.EncodeToString(signature)
err = os.WriteFile(outputName, []byte(signatureBase64), 0644)
if err != nil {
fmt.Println("Failed to save signature:", err)
return
}
fmt.Println("Files signed successfully.")
}
func verifySignatureFiles(fileNames, signatureName, keyName string) {
publicKeyPEM, err := os.ReadFile(keyName + ".pub")
if err != nil {
fmt.Println("Failed to read public key:", err)
return
}
block, _ := pem.Decode(publicKeyPEM)
if block == nil || block.Type != "RSA PUBLIC KEY" {
fmt.Println("Invalid public key")
return
}
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
fmt.Println("Failed to parse public key:", err)
return
}
publicKey, ok := publicKeyInterface.(*rsa.PublicKey)
if !ok {
fmt.Println("Invalid public key")
return
}
files := strings.Split(fileNames, " ")
if len(files) == 0 {
fmt.Println("No files specified")
return
}
fileData := make([]byte, 0)
for _, fileName := range files {
data, err := os.ReadFile(fileName)
if err != nil {
fmt.Println("Failed to read file:", err)
return
}
fileData = append(fileData, data...)
}
hash := sha256.Sum256(fileData)
signatureBase64, err := os.ReadFile(signatureName)
if err != nil {
fmt.Println("Failed to read signature:", err)
return
}
signature, err := base64.StdEncoding.DecodeString(string(signatureBase64))
if err != nil {
fmt.Println("Failed to decode signature:", err)
return
}
err = rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hash[:], signature)
if err != nil {
fmt.Println("Signature verification failed:", err)
return
}
fmt.Println("Signature verified successfully.")
}
func encodeFile(fileName, keyName, outputFileName string) {
file, err := os.Open(fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
publicKeyPEM, err := os.ReadFile(keyName + ".pub")
if err != nil {
log.Fatal(err)
}
block, _ := pem.Decode(publicKeyPEM)
if block == nil || block.Type != "RSA PUBLIC KEY" {
log.Fatal("Failed to decode public key")
}
publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
log.Fatal(err)
}
rsaPublicKey := publicKey.(*rsa.PublicKey)
outputFile, err := os.Create(outputFileName)
if err != nil {
log.Fatal(err)
}
defer outputFile.Close()
buffer := make([]byte, chunkSizeEncode)
for {
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
log.Fatal(err)
}
if n == 0 {
break
}
encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, buffer[:n])
if err != nil {
log.Fatal(err)
}
_, err = outputFile.Write(encryptedData)
if err != nil {
log.Fatal(err)
}
}
fmt.Printf("File %s encrypted successfully. Encrypted data saved as %s\n", fileName, outputFileName)
}
func decodeFile(fileName, keyName, outputFileName string) {
file, err := os.Open(fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
privateKeyPEM, err := os.ReadFile(keyName + ".scrkey")
if err != nil {
log.Fatal(err)
}
block, _ := pem.Decode(privateKeyPEM)
if block == nil || block.Type != "RSA PRIVATE KEY" {
log.Fatal("Failed to decode private key")
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
log.Fatal(err)
}
outputFile, err := os.Create(outputFileName)
if err != nil {
log.Fatal(err)
}
defer outputFile.Close()
buffer := make([]byte, chunkSizeDecode)
for {
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
log.Fatal(err)
}
if n == 0 {
break
}
decryptedData, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, buffer[:n])
if err != nil {
log.Fatal(err)
}
_, err = outputFile.Write(decryptedData)
if err != nil {
log.Fatal(err)
}
}
fmt.Printf("File %s decrypted successfully. Decrypted data saved as %s\n", fileName, outputFileName)
}