Created
December 14, 2024 11:28
-
-
Save akbariandev/4cac5b4c496b6a68aab08eb3548ed836 to your computer and use it in GitHub Desktop.
3DES Encryption
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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