Skip to content

Instantly share code, notes, and snippets.

@akbariandev
Created December 14, 2024 11:28
Show Gist options
  • Save akbariandev/4cac5b4c496b6a68aab08eb3548ed836 to your computer and use it in GitHub Desktop.
Save akbariandev/4cac5b4c496b6a68aab08eb3548ed836 to your computer and use it in GitHub Desktop.
3DES Encryption
package _3DES
import (
"bytes"
"crypto/cipher"
"crypto/des"
)
// Encrypt using 3DES
func Encrypt(input, key []byte) ([]byte, error) {
block, err := des.NewTripleDESCipher(key)
if err != nil {
return nil, err
}
bs := block.BlockSize()
iv := make([]byte, bs)
padding := bs - len(input)%bs
paddedInput := append(input, bytes.Repeat([]byte{byte(padding)}, padding)...)
cipherInput := make([]byte, len(paddedInput))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherInput, paddedInput)
return cipherInput, nil
}
// Decrypt using 3DES
func Decrypt(input, key []byte) ([]byte, error) {
block, err := des.NewTripleDESCipher(key)
if err != nil {
return nil, err
}
iv := make([]byte, block.BlockSize())
mode := cipher.NewCBCDecrypter(block, iv)
paddedInput := make([]byte, len(input))
mode.CryptBlocks(paddedInput, input)
padding := paddedInput[len(paddedInput)-1]
decrypted := paddedInput[:len(paddedInput)-int(padding)]
return decrypted, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment