|
| 1 | +package httpsms |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/aes" |
| 5 | + "crypto/cipher" |
| 6 | + "crypto/rand" |
| 7 | + "crypto/sha256" |
| 8 | + "encoding/base64" |
| 9 | + "errors" |
| 10 | +) |
| 11 | + |
| 12 | +// CipherService is used to encrypt and decrypt SMS messages using the AES-256 algorithm |
| 13 | +type CipherService service |
| 14 | + |
| 15 | +// Encrypt the message content using the encryption key |
| 16 | +func (service *CipherService) Encrypt(encryptionKey string, content string) (string, error) { |
| 17 | + block, err := aes.NewCipher(service.hash(encryptionKey)) |
| 18 | + if err != nil { |
| 19 | + return "", errors.Join(err, errors.New("failed to create new cipher")) |
| 20 | + } |
| 21 | + |
| 22 | + text := []byte(content) |
| 23 | + |
| 24 | + iv, err := service.initializationVector() |
| 25 | + if err != nil { |
| 26 | + return "", errors.Join(err, errors.New("failed to create initialization vector")) |
| 27 | + } |
| 28 | + |
| 29 | + stream := cipher.NewCFBEncrypter(block, iv) |
| 30 | + cipherText := make([]byte, len(text)) |
| 31 | + stream.XORKeyStream(cipherText, text) |
| 32 | + |
| 33 | + return base64.StdEncoding.EncodeToString(append(iv, cipherText...)), nil |
| 34 | +} |
| 35 | + |
| 36 | +// Decrypt the message content using the encryption key |
| 37 | +func (service *CipherService) Decrypt(encryptionKey string, cipherText string) (string, error) { |
| 38 | + content, err := base64.StdEncoding.DecodeString(cipherText) |
| 39 | + if err != nil { |
| 40 | + return "", errors.Join(err, errors.New("failed to decode cipher in base64")) |
| 41 | + } |
| 42 | + |
| 43 | + block, err := aes.NewCipher(service.hash(encryptionKey)) |
| 44 | + if err != nil { |
| 45 | + return "", errors.Join(err, errors.New("failed to create new cipher")) |
| 46 | + } |
| 47 | + |
| 48 | + // Decrypt the message |
| 49 | + cipherTextBytes := content[16:] |
| 50 | + stream := cipher.NewCFBDecrypter(block, content[:16]) |
| 51 | + stream.XORKeyStream(cipherTextBytes, cipherTextBytes) |
| 52 | + |
| 53 | + return string(cipherTextBytes), nil |
| 54 | +} |
| 55 | + |
| 56 | +// hash a key using the SHA-256 algorithm |
| 57 | +func (service *CipherService) hash(key string) []byte { |
| 58 | + sha := sha256.Sum256([]byte(key)) |
| 59 | + return sha[:] |
| 60 | +} |
| 61 | + |
| 62 | +func (service *CipherService) initializationVector() ([]byte, error) { |
| 63 | + iv := make([]byte, 16) |
| 64 | + _, err := rand.Read(iv) |
| 65 | + return iv, err |
| 66 | +} |
0 commit comments