-
Notifications
You must be signed in to change notification settings - Fork 0
/
api-ofb-file.go
111 lines (86 loc) · 2.28 KB
/
api-ofb-file.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
/*
* Golang presentation
*
* @package main
* @author @jeffotoni
* @size 2017
*/
package gcry
import (
"crypto/aes"
"crypto/cipher"
"fmt"
"io"
"os"
"strings"
)
func EncryptOFBFile(fileName string) string {
key := []byte(KEY)
if !FileExists(fileName) {
fmt.Println("error file not exist!")
}
inFile, err := os.Open(fileName)
if err != nil {
fmt.Println(err)
}
defer inFile.Close()
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println(err)
}
// If the key is unique for each ciphertext, then it's ok to use a zero
// IV.
var iv [aes.BlockSize]byte
stream := cipher.NewOFB(block, iv[:])
fileNameCry := fileName + ".cry"
outFile, err := os.OpenFile(fileNameCry, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
fmt.Println(err)
}
defer outFile.Close()
writer := &cipher.StreamWriter{S: stream, W: outFile}
// Copy the input file to the output file, encrypting as we go.
if _, err := io.Copy(writer, inFile); err != nil {
fmt.Println(err)
}
return fileNameCry
// Note that this example is simplistic in that it omits any
// authentication of the encrypted data. If you were actually to use
// StreamReader in this manner, an attacker could flip arbitrary bits in
// the decrypted result.
}
//
//
//
func DecryptOFBFile(fileName string) string {
key := []byte(KEY)
inFile, err := os.Open(fileName)
if err != nil {
fmt.Println(err)
}
defer inFile.Close()
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println(err)
}
// If the key is unique for each ciphertext, then it's ok to use a zero
// IV.
var iv [aes.BlockSize]byte
stream := cipher.NewOFB(block, iv[:])
fileNameDecrypt := strings.Trim(fileName, ".cry")
outFile, err := os.OpenFile(fileNameDecrypt, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
fmt.Println(err)
}
defer outFile.Close()
reader := &cipher.StreamReader{S: stream, R: inFile}
// Copy the input file to the output file, decrypting as we go.
if _, err := io.Copy(outFile, reader); err != nil {
fmt.Println(err)
}
return "done: " + fileNameDecrypt
// Note that this example is simplistic in that it omits any
// authentication of the encrypted data. If you were actually to use
// StreamReader in this manner, an attacker could flip arbitrary bits in
// the output.
}