-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
75 lines (72 loc) · 1.81 KB
/
crypto.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
/*
* This file contains all the cryptographi operations
* to work with ENCRL, for example the encrypt function.
* */
package main
import (
"fmt"
)
func reverseCipher(cipher map[string]string) map[string]string{
/*
* This functions uses a chipher and reverse its, so for example:
*
* {
* "a": 1,
* "b": 2,
* ...
* }
*
* Converts to:
* {
* 1: "a",
* 2: "b",
* }
*
* Parameters:
* cipher -> The cipher to reverse
*
* Returns:
* The reversed cipher
* */
reversed := make(map[string]string)
for key, value := range cipher {
reversed[value] = key
}
return reversed
}
func encrypt(decrypt bool, cipher map[string]string, file []byte) []byte{
/*
* This function is used to codificate a file using a given cipher
*
* Parameters:
* decrypt -> A flag fvariable for encrypt / decrypt
* cipher -> The cipher to use when codificating (see more at ~/codiffications/ )
* file -> An array of bytes with the content of the fyle to encrypt
*
* Returns:
* An array of bytes that represent the new content of the file
*
* */
var charsCount uint
var modifiedFile []byte
// Reverse the cipher if it's needed
if decrypt {
cipher = reverseCipher(cipher)
}
for _, letter := range file {
charsCount++
value, exists := cipher[string(letter)]
if exists {
for i := 0; i < len(value); i++ {
modifiedFile = append(modifiedFile, value[i])
}
} else {
// If the character is not located in the codification, set the new value
// to the old letter
modifiedFile = append(modifiedFile, letter)
}
}
fmt.Printf("[ENCRYPTION]: Total modified characters %d.\n", charsCount)
fmt.Printf("[ENCRYPTION]: Byte array with the encryption loaded correctly.")
return modifiedFile
}