Esempio n. 1
0
func AESEncryptBytes(block cipher.Block, plain []byte) (cipherBytes []byte, err error) {
	blockSize := block.BlockSize()
	plain = utils.PadBytes(plain, blockSize)
	length := len(plain)

	// Encrypt
	cipherBytes = make([]byte, length)
	for i := 0; i < length; i += blockSize {
		block.Encrypt(cipherBytes[i:i+blockSize], plain[i:i+blockSize])
	}

	return
}
Esempio n. 2
0
func AESDecryptBytes(block cipher.Block, cipherBytes []byte) (plain []byte, err error) {
	defer func() {
		if e := recover(); e != nil {
			plain = nil
			err = fmt.Errorf("%v", e)
		}
	}()

	blockSize := block.BlockSize()
	cipherBytes = utils.PadBytes(cipherBytes, blockSize)
	length := len(cipherBytes)

	// Decrypt
	plain = make([]byte, length)
	for i := 0; i < length; i += blockSize {
		block.Decrypt(plain[i:i+blockSize], cipherBytes[i:i+blockSize])
	}

	return
}
func main() {
	msg := []byte("This is 18+ chars!")
	fmt.Printf("msg ==    %s\n", msg)

	// Encrypt
	encBlock, err := aes.NewCipher(PASSPHRASE)
	fun.MaybeFatalAt("aes.NewCipher", err)

	// See https://github.com/thecloakproject/utils/blob/master/crypt/aes.go
	cipher, err := crypt.AESEncryptBytes(encBlock, msg)
	fun.MaybeFatalAt("AESEncryptBytes", err)

	fmt.Printf("cipher == %v\n", cipher)

	// Decrypt
	decBlock, err := aes.NewCipher(PASSPHRASE)
	fun.MaybeFatalAt("aes.NewCipher", err)

	// See https://github.com/thecloakproject/utils/blob/master/crypt/aes.go
	plain, err := crypt.AESDecryptBytes(decBlock, cipher)
	fun.MaybeFatalAt("AESDecryptBytes", err)

	fmt.Printf("plain ==  %s\n", plain)
	msgPadded := utils.PadBytes(msg, decBlock.BlockSize())

	// Check for equality
	fmt.Printf("\nThey match? %v!\n", bytes.Equal(msgPadded, plain))

	// Check for equality in other ways
	msgUnpadded := strings.TrimSpace(string(msgPadded))
	match := (msgUnpadded == string(plain))
	fmt.Printf("\nDo their trimmed versions match? %v!\n", match)
	if match {
		fmt.Printf("They both equal '%s'\n", msgUnpadded)
	}

	// Here's how to remove those ugly trailing nulls
	fmt.Printf("Cleanest-looking version: '%s'\n",
		strings.TrimRight(string(plain), "\x00"))
}