// encrypt string to base64 crypto using AES
func encrypt(key []byte, text string) string {
	// key := []byte(keyText)
	plaintext := []byte(text)

	block, err := aes.NewCipher(key)
	if err != nil {
		log.Error(err)
		return ""
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		log.Error(err)
		return ""
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

	// convert to base64
	return base64.URLEncoding.EncodeToString(ciphertext)
}
Example #2
0
func AESCtyptTest() {
	fmt.Println("AES测试")
	//需要去加密的字符串
	plaintext := []byte("My name is daniel")

	//aes的加密字符串
	key_text := "astaxie12798akljzmknm.ahkjkljl;k"

	fmt.Println(len(key_text))

	// 创建加密算法aes
	c, err := aes.NewCipher([]byte(key_text))
	if err != nil {
		fmt.Printf("Error: NewCipher(%d bytes) = %s", len(key_text), err)
		return
	}

	//加密字符串
	cfb := cipher.NewCFBEncrypter(c, commonIV)
	ciphertext := make([]byte, len(plaintext))
	cfb.XORKeyStream(ciphertext, plaintext)
	fmt.Printf("%s=>%x\n", plaintext, ciphertext)

	// 解密字符串
	cfbdec := cipher.NewCFBDecrypter(c, commonIV)
	plaintextCopy := make([]byte, len(plaintext))
	cfbdec.XORKeyStream(plaintextCopy, ciphertext)
	fmt.Printf("%x=>%s\n", ciphertext, plaintextCopy)
}
Example #3
0
// Method Close encrypts and writes the encrypted data to the key file
func (k *KeyStore) Close(secret []byte) {
	// Encode a gob of the keystore
	var buff bytes.Buffer
	enc := gob.NewEncoder(&buff)
	enc.Encode(k)
	buffString := buff.String()

	// Encrypt the data
	block, err := aes.NewCipher(secret)
	if err != nil {
		panic(err)
	}
	ciphertext := make([]byte, aes.BlockSize+len(buffString))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}
	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(buffString))

	// Write the encrypted data to the file
	kFile, err := os.OpenFile(kf, os.O_WRONLY, 0644)
	if err != nil {
		panic(err)
	}
	bytesWritten, err := kFile.Write(ciphertext)
	if err != nil || bytesWritten == 0 {
		panic(err)
	}
}
Example #4
0
func AesEncryptData(data, key []byte, ctp string) []byte {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	data_enc := make([]byte, aes.BlockSize+len(data))
	iv := data_enc[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil
	}

	var stream cipher.Stream
	switch ctp {
	case "cfb":
		stream = cipher.NewCFBEncrypter(block, iv)
	case "ctr":
		stream = cipher.NewCTR(block, iv)
	default:
		stream = cipher.NewOFB(block, iv)
	}
	stream.XORKeyStream(data_enc[aes.BlockSize:], data)

	// It's important to remember that ciphertexts must be authenticated
	// (i.e. by using crypto/hmac) as well as being encrypted in order to
	// be secure.

	return data_enc
}
Example #5
0
func (self *defaultAuther) encodeTicket(userdata string, expiryMinutes int64) string {

	// generate the token uuid|userdata|expiry

	uuid := Uuid()
	time := time.Now().Add(time.Duration(expiryMinutes) * time.Minute).Format(time.RFC3339)

	token := fmt.Sprintf("%s|%s|%s", uuid, userdata, time)

	// encrypt the token

	block, blockError := aes.NewCipher(self.key)

	if nil != blockError {
		return ""
	}

	bytes := []byte(token)
	encrypted := make([]byte, len(bytes))

	encrypter := cipher.NewCFBEncrypter(block, self.key[:aes.BlockSize])
	encrypter.XORKeyStream(encrypted, bytes)

	return hex.EncodeToString(encrypted)
}
Example #6
0
func main() {
	plainText := []byte("Bob loves Alice.")
	key := []byte("passw0rdpassw0rdpassw0rdpassw0rd")

	// Create new DES cipher block
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Printf("err: %s\n", err)
	}

	// The IV (Initialization Vector) need to be unique, but not secure.
	// Therefore, it's common to include it at the beginning of the cipher text.
	cipherText := make([]byte, aes.BlockSize+len(plainText))

	// Create IV
	iv := cipherText[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		fmt.Printf("err: %s\n", err)
	}

	// Encrypt
	encryptStream := cipher.NewCFBEncrypter(block, iv)
	encryptStream.XORKeyStream(cipherText[aes.BlockSize:], plainText)
	fmt.Printf("Cipher text: %v\n", cipherText)

	// Decrpt
	decryptedText := make([]byte, len(cipherText[aes.BlockSize:]))
	decryptStream := cipher.NewCFBDecrypter(block, cipherText[:aes.BlockSize])
	decryptStream.XORKeyStream(decryptedText, cipherText[aes.BlockSize:])
	fmt.Printf("Decrypted text: %s\n", string(decryptedText))
}
Example #7
0
// NewAesEncryptionStream creates a new AES description stream based on given key and IV.
// Caller must ensure the length of key and IV is either 16, 24 or 32 bytes.
func NewAesEncryptionStream(key []byte, iv []byte) cipher.Stream {
	aesBlock, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}
	return cipher.NewCFBEncrypter(aesBlock, iv)
}
Example #8
0
func NewChiper(algo, secret string) (*Cipher, error) {
	if algo == "rc4" {
		c, err := rc4.NewCipher(truncateSecretToSize(secret, 32))
		if err != nil {
			return nil, err
		}
		return &Cipher{
			enc: c,
			dec: c,
		}, nil
	} else if algo == "aes" {
		key := truncateSecretToSize(secret, 32)
		c, err := aes.NewCipher(key)
		if err != nil {
			return nil, err
		}
		return &Cipher{
			enc: cipher.NewCFBEncrypter(c, key[:c.BlockSize()]),
			dec: cipher.NewCFBDecrypter(c, key[:c.BlockSize()]),
		}, nil
	}

	cipher, err := rc4.NewCipher([]byte(secret))
	if err != nil {
		return nil, err
	}
	return &Cipher{
		enc: cipher,
		dec: cipher,
	}, nil
}
Example #9
0
// encryptAES enrypts plaintext input with passed key, IV and mode in AES block cipher;
// and returns ciphertext output
func encryptAES(input []byte, output []byte, key, iv []byte, mode Mode) error {
	block, err := aes.NewCipher(key)
	if err != nil {
		return errors.New("Couldn't create block cipher.")
	}

	// Prepend IV to ciphertext.
	// Generate IV randomly if it is not passed
	if iv == nil {
		if iv = generateIV(aes.BlockSize); iv == nil {
			return errors.New("Couldn't create random initialization vector (IV).")
		}
	}
	copy(output, iv)

	switch mode {
	case CBC:
		if len(input)%aes.BlockSize != 0 {
			input = addPadding(input, aes.BlockSize)
		}
		mode := cipher.NewCBCEncrypter(block, iv)
		mode.CryptBlocks(output[aes.BlockSize:], input)
	case CFB:
		mode := cipher.NewCFBEncrypter(block, iv)
		mode.XORKeyStream(output[aes.BlockSize:], input)
	case CTR:
		mode := cipher.NewCTR(block, iv)
		mode.XORKeyStream(output[aes.BlockSize:], input)
	case OFB:
		mode := cipher.NewOFB(block, iv)
		mode.XORKeyStream(output[aes.BlockSize:], input)
	}
	return nil
}
Example #10
0
File: aes.go Project: kingfree/haut
func main() {
	// 原文本
	pliantext := []byte("遊ぼうよ、和と")
	if len(os.Args) > 1 {
		pliantext = []byte(os.Args[1])
	}
	Println("原文本:", string(pliantext))
	// 加密盐 长度必须为 16B(128b), 24B(192b), 32B(256b)
	key_text := "最高の奇跡に乗り込め!!"
	if len(os.Args) > 2 {
		key_text = os.Args[2]
	}
	Println("盐", len(key_text), ":", key_text)
	// 加密算法
	c, err := aes.NewCipher([]byte(key_text))
	if err != nil {
		Printf("错误:NewCipher(%dB) = %s\n", len(key_text), err)
		os.Exit(1)
	}
	// 实行加密
	cfb := cipher.NewCFBEncrypter(c, commonIV)
	ciphertext := make([]byte, len(pliantext))
	cfb.XORKeyStream(ciphertext, pliantext)
	Printf("%s=>%x\n", pliantext, ciphertext)
	// 实行解密
	cfbdec := cipher.NewCFBDecrypter(c, commonIV)
	gettext := make([]byte, len(pliantext))
	cfbdec.XORKeyStream(gettext, ciphertext)
	Printf("%x=>%s\n", ciphertext, gettext)
}
Example #11
0
func encryptFile(path string) {
	fmt.Printf("  Lock: %s\n", path)

	plaintext, err := ioutil.ReadFile(path)
	if err != nil {
		panic(err.Error())
	}

	byteKey := sha256.Sum256([]byte(*key))
	block, err := aes.NewCipher(byteKey[:])
	if err != nil {
		panic(err)
	}

	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

	f, err := os.Create(path + ".aes")
	if err != nil {
		panic(err.Error())
	}
	_, err = io.Copy(f, bytes.NewReader(ciphertext))
	if err != nil {
		panic(err.Error())
	}
	os.Remove(path)
}
Example #12
0
func Encrypt(in io.Reader, key string) io.Reader {

	// Convert io.Reader to string
	buf := new(bytes.Buffer)
	buf.ReadFrom(in)
	s := buf.String()

	// Load the plaintext message you want to encrypt.
	plaintext := []byte(s)

	// Setup a key that will encrypt the other text.
	h := sha256.New()
	io.WriteString(h, key)
	key_text := h.Sum(nil)

	// We chose our cipher type here in this case we are using AES.
	c, err := aes.NewCipher([]byte(key_text))
	if err != nil {
		fmt.Printf("Error: NewCipher(%d bytes) = %s", len(key_text), err)
		os.Exit(-1)
	}

	// We use the CFBEncrypter in order to encrypt
	// the whole stream of plaintext using the
	// cipher setup with c and a iv.
	cfb := cipher.NewCFBEncrypter(c, commonIV)
	ciphertext := make([]byte, len(plaintext))
	cfb.XORKeyStream(ciphertext, plaintext)
	return strings.NewReader(string(ciphertext))
}
Example #13
0
func encryptToBase64(content string, k string) string {
	var commonIV = []byte{0x1f, 0x2c, 0x49, 0xea, 0xb5, 0xf3, 0x47, 0x2e, 0xa8, 0x71, 0x0a, 0xc0, 0x4e, 0x5d, 0x83, 0x19}
	plaintext := []byte(content)
	key_salt := "3z0RlwtvIOdlC8aAwIaCbX0D"
	var key_text string
	if len(k) < 24 {
		key_text = k + key_salt[len(k):]
	}
	if len(k) > 24 {
		key_text = k[:24]
	}

	c, err := aes.NewCipher([]byte(key_text))
	if err != nil {
		fmt.Printf("Error: NewCipher(%d bytes) = %s", len(key_text), err)
		os.Exit(-1)
	}

	cfb := cipher.NewCFBEncrypter(c, commonIV)
	ciphertext := make([]byte, len(plaintext))
	cfb.XORKeyStream(ciphertext, plaintext)

	base64Text := base64.StdEncoding.EncodeToString(ciphertext)
	return string(base64Text)
}
Example #14
0
func FakioDial(server string, req []byte) (c *FakioConn, err error) {
	conn, err := net.Dial("tcp", server)
	if err != nil {
		return nil, err
	}

	//handshake
	key := stringToKey(fclient.PassWord)

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	enc := cipher.NewCFBEncrypter(block, req[0:16])

	// 22 = iv + username
	index := 16 + int(req[16]) + 1
	enc.XORKeyStream(req[index:], req[index:])
	if _, err := conn.Write(req); err != nil {
		return nil, errors.New("handshake to server error")
	}

	hand := make([]byte, 64)
	if _, err := conn.Read(hand); err != nil {
		return nil, errors.New("handshake to server error")
	}

	dec := cipher.NewCFBDecrypter(block, hand[0:16])
	dec.XORKeyStream(hand[16:], hand[16:])

	cipher, err := NewCipher(hand[16:])

	return &FakioConn{conn, cipher}, nil
}
Example #15
0
// Bagla encrypts the text with the given key.
func Bagla(key string, text string) (string, error) {

	k := len(key)
	switch k {
	default:
		return "", errors.New("key length must be 16, 24 or 32")
	case 16, 24, 32:
		break
	}

	plaintext := []byte(text)

	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return "", err
	}

	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return "", err
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

	return base64.StdEncoding.EncodeToString(ciphertext), nil
}
Example #16
0
func ParameterizedEncrypt(password []byte, payload []byte, iter int, keyLen int) ([]byte, error) {
	salt, salt_error := GetRandom(salt_size)
	if salt_error != nil {
		return nil, salt_error
	}
	key, key_error := GenKey(password, salt, iter, keyLen)
	if key_error != nil {
		return nil, key_error
	}

	c, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	iv, iv_err := GetRandom(c.BlockSize())
	if iv_err != nil {
		return nil, iv_err
	}

	result := make([]byte, 0, len(payload)+len(salt)+len(iv)+8+3+3)
	result = append(result, salt...)
	result = append(result, []byte(injectInt(iter, 8)+injectInt(keyLen, 3)+injectInt(len(iv), 3))...)
	result = append(result, iv...)

	return append(result, xorKeyStream(cipher.NewCFBEncrypter(c, iv), payload)...), nil
}
Example #17
0
func decode(data []byte, encrypt_key string, encrypt_iv string, attr ContentAttribute) ([]byte, error) {

	if attr.Compressed() {
		r, err := zlib.NewReader(bytes.NewReader(data))
		if err != nil {
			return nil, err
		}

		buf := bytes.NewBuffer(nil)
		_, err = io.Copy(buf, r)
		if err != nil {
			return nil, err
		}

		r.Close()
		data = buf.Bytes()
	}

	if attr.Crypted() {
		block, err := aes.NewCipher([]byte(encrypt_key))
		if err != nil {
			return nil, err
		}
		cfb := cipher.NewCFBEncrypter(block, []byte(encrypt_iv))
		cipher_data := make([]byte, len(data))
		cfb.XORKeyStream(cipher_data, data)
		data = cipher_data
	}

	return data, nil
}
Example #18
0
File: aes.go Project: dulumao/ant
func AESEncrypt(s string, key string) (c string, err error) {
	var k []byte
	var block cipher.Block
	var cfb cipher.Stream
	var cb []byte
	var iv []byte

	k = AESMake256Key(key)

	block, err = aes.NewCipher(k)
	if err != nil {
		return
	}

	cb = make([]byte, aes.BlockSize+len(s))
	iv = cb[:aes.BlockSize]
	_, err = io.ReadFull(rand.Reader, iv)
	if err != nil {
		return
	}

	cfb = cipher.NewCFBEncrypter(block, iv)
	cfb.XORKeyStream(cb[aes.BlockSize:], bytes.NewBufferString(s).Bytes())

	c = hex.EncodeToString(cb)
	return
}
Example #19
0
func Encrypt(key string, privatekey PrivateKey, win io.Writer, length, sequence int64) (w io.Writer, e os.Error) {
	c, e := simpleCipher(key)
	if e != nil {
		return
	}
	priv, e := readRSAKey(privatekey)
	if e != nil {
		return
	}
	iv := make([]byte, c.BlockSize())
	_, e = rand.Read(iv)
	if e != nil {
		return
	}
	_, e = win.Write(iv) // pass the iv across first
	if e != nil {
		return
	}
	wraw := cipher.StreamWriter{cipher.NewCFBEncrypter(c, iv), win, nil}
	wenc := flate.NewWriter(wraw, flate.BestCompression)
	e = binary.Write(wenc, binary.LittleEndian, length)
	if e != nil {
		return
	}
	e = binary.Write(wenc, binary.LittleEndian, sequence)
	if e != nil {
		return
	}
	return &hashWriter{wenc, wraw, sha256.New(), priv, length}, nil
}
Example #20
0
func createEncryptor(keySource, ivSource []byte, output io.Writer) (writer io.Writer, key string, err error) {

	// Need at least 32 bytes of the key source
	if len(keySource) < 32 {
		err = ErrInsufficientKeySource
		return
	}

	// Create the iv
	var iv [16]byte
	for i, b := range ivSource {
		iv[i] = b
		if i >= 15 {
			break
		}
	}

	keyRaw := keySource[:32]
	key = cipherAES256Hex + hex.EncodeToString(keyRaw)

	// Generate the encrypted content
	blobCipher, err := aes.NewCipher(keyRaw)
	if err != nil {
		return
	}

	// Generate the writer
	writer = &cipher.StreamWriter{
		S: cipher.NewCFBEncrypter(
			blobCipher,
			iv[:]),
		W: output}

	return
}
Example #21
0
func EncryptAESCFB(src *AuthToken, key []byte) []byte {
	var err error
	rawData := RawData{}

	rawData.Data, err = json.Marshal(src)
	if err != nil {
		panic(err)
	}
	rawData.CSum = crc32.ChecksumIEEE(rawData.Data)

	rawBytes, err := json.Marshal(rawData)
	encrData := EncrData{
		IV:   randStr(len(key)),
		Data: make([]byte, len(rawBytes)),
	}

	cipher.NewCFBEncrypter(aesCipher(key), encrData.IV).XORKeyStream(encrData.Data, rawBytes)

	encrBytes, err := json.Marshal(encrData)
	if err != nil {
		panic(err)
	}

	return encrBytes
}
Example #22
0
func main() {
	//需要去加密的字符串
	plaintext := []byte("My name is Astaxie")
	//如果传入加密串的话,plaint就是传入的字符串
	if len(os.Args) > 1 {
		plaintext = []byte(os.Args[1])
	}

	//des的加密字符串
	key_text := "12345678"
	if len(os.Args) > 2 {
		key_text = os.Args[2]
	}

	fmt.Println(len(key_text))

	// 创建加密算法des
	c, err := des.NewCipher([]byte(key_text))
	if err != nil {
		fmt.Printf("Error: NewCipher(%d bytes) = %s", len(key_text), err)
		os.Exit(-1)
	}

	//加密字符串
	cfb := cipher.NewCFBEncrypter(c, commonIV)
	ciphertext := make([]byte, len(plaintext))
	cfb.XORKeyStream(ciphertext, plaintext)
	fmt.Printf("%s=>%x\n", plaintext, ciphertext)

	// 解密字符串
	cfbdec := cipher.NewCFBDecrypter(c, commonIV)
	plaintextCopy := make([]byte, len(plaintext))
	cfbdec.XORKeyStream(plaintextCopy, ciphertext)
	fmt.Printf("%x=>%s\n", ciphertext, plaintextCopy)
}
Example #23
0
func AesEncryptFd(inFile, outFile *os.File, key, iv []byte, ctp int) error {
	block, err := aes.NewCipher(key)
	if err != nil {
		return err
	}

	var stream cipher.Stream
	switch ctp {
	case 1:
		stream = cipher.NewCFBEncrypter(block, iv[:])
	case 2:
		stream = cipher.NewCTR(block, iv[:])
	default:
		stream = cipher.NewOFB(block, iv[:])
	}

	writer := &cipher.StreamWriter{S: stream, W: outFile}
	// Copy the input file to the output file, encrypting as we go.
	if _, err := io.Copy(writer, inFile); err != nil {
		return err
	}

	// Note that this example is simplistic in that it omits any
	// authentication of the encrypted data. If you were actually to use
	// StreamReader in this manner, an attacker could flip arbitrary bits in
	// the decrypted result.
	return nil
}
Example #24
0
func sc_aes_crypt(isEncrypt bool, engine_boots, engine_time int, msg_salt, key, data []byte) error {

	if 0 == len(data) {
		return fmt.Errorf("len(input_data) != 0, actual len is 0")
	}

	if 8 != len(msg_salt) {
		return fmt.Errorf("len(msg_salt) != 8, actual len is %d", len(msg_salt))
	}
	initVec := make([]byte, 8+len(msg_salt))

	binary.BigEndian.PutUint32(initVec, uint32(engine_boots))
	binary.BigEndian.PutUint32(initVec[4:], uint32(engine_time))
	copy(initVec[8:], msg_salt)

	block, err := aes.NewCipher(key)
	if nil != err {
		return err
	}
	if isEncrypt {
		cipher.NewCFBEncrypter(block, initVec).
			XORKeyStream(data, data)
	} else {
		cipher.NewCFBDecrypter(block, initVec).
			XORKeyStream(data, data)
	}
	return nil
}
Example #25
0
/*
KeyedPRF is a psuedo random function. It hashes the input, pads it to
the correct output length, and then encrypts it with AES. Finally it
checks that the result is within the desired range. If it is it returns
 the value as a long integer, if it isn't, it increments a nonce in the
input and recalculates until it finds an integer in the given range
*/
func keyedPRFBig(key []byte, r *big.Int, x int) (*big.Int, error) {
	aesBlockEncrypter, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, make([]byte, aes.BlockSize))
	hash := sha256.New()
	var num big.Int
	result := make([]byte, r.BitLen()>>3)
	for nonce := 0; ; nonce++ {
		hash.Reset()
		hash.Write([]byte(strconv.Itoa(x + nonce)))
		h := hash.Sum(nil)
		if r.BitLen() > 32*8 {
			len := 32 - uint((r.BitLen()+7)>>3)
			h = append(h, make([]byte, len)...)
		}
		if r.BitLen() < 32*8 {
			len := uint((r.BitLen() + 7) >> 3)
			h = h[:len]
		}
		aesEncrypter.XORKeyStream(result, h)
		num.SetBytes(result)
		if num.Cmp(r) < 0 {
			break
		}
	}
	return &num, nil
}
Example #26
0
func (d *defaultFactory) CreateEncryptor(keySource, ivSource []byte, output io.Writer) (writer io.Writer, key string, err error) {

	// Need at least 32 bytes of the key source
	if len(keySource) < cipherAES256KeySourceLength {
		err = ErrInsufficientKeySource
		return
	}

	// Create the iv
	var iv [aes.BlockSize]byte
	copy(iv[:], ivSource)

	// Create AES-compatible key
	keyRaw := keySource[:cipherAES256KeySourceLength]
	key = cipherAES256Hex + hex.EncodeToString(keyRaw)

	// Generate the encrypted content
	blobCipher, err := aes.NewCipher(keyRaw)
	if err != nil {
		return
	}

	// Generate the writer
	writer = &cipher.StreamWriter{
		S: cipher.NewCFBEncrypter(
			blobCipher,
			iv[:]),
		W: output}

	return
}
Example #27
0
func encrypt(key []byte, text string) (string, error) {

	if text == "" || text == "{}" {
		return "", nil
	}

	plaintext := []byte(text)
	skey := sha512.Sum512(key)
	ekey, akey := skey[:32], skey[32:]

	block, err := aes.NewCipher(ekey)
	if err != nil {
		return "", err
	}

	macfn := hmac.New(sha256.New, akey)
	ciphertext := make([]byte, aes.BlockSize+macfn.Size()+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(crand.Reader, iv); err != nil {
		return "", err
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize+macfn.Size():], plaintext)
	macfn.Write(ciphertext[aes.BlockSize+macfn.Size():])
	mac := macfn.Sum(nil)
	copy(ciphertext[aes.BlockSize:aes.BlockSize+macfn.Size()], mac)

	return base64.URLEncoding.EncodeToString(ciphertext), nil
}
Example #28
0
func (b *Bucket) Decode(data []byte, attr ContentAttribute) ([]byte, error) {

	if attr.Compressed() {
		var buf bytes.Buffer
		r, err := zlib.NewReader(bytes.NewReader(data))
		if err != nil {
			return nil, err
		}
		r.Read(data)
		r.Close()
		data = buf.Bytes()
	}

	if attr.Crypted() {
		block, err := aes.NewCipher([]byte(Option.EncryptKey))
		if err != nil {
			return nil, err
		}
		cfb := cipher.NewCFBEncrypter(block, []byte(Option.EncryptIv))
		cipher_data := make([]byte, len(data))
		cfb.XORKeyStream(cipher_data, data)
		data = cipher_data
	}

	return data, nil
}
Example #29
0
func saveServices(passwd string, services *Services) {
	sort.Sort(services)
	decryptedBuffer := bytes.NewBuffer(nil)
	err := json.NewEncoder(decryptedBuffer).Encode(services)
	gobro.CheckErr(err)

	blockCipher, err := blowfish.NewCipher([]byte(passwd))
	gobro.CheckErr(err)
	iv := make([]byte, 8)
	_, err = rand.Read(iv)
	gobro.CheckErr(err)

	enc := decryptedBuffer.Bytes()
	cipher.NewCFBEncrypter(blockCipher, iv).XORKeyStream(enc, enc)
	buff := bytes.NewBuffer(iv)
	_, err = buff.Write(enc)
	gobro.CheckErr(err)

	enc = append(iv, enc...)
	base64EncodedLen := base64.StdEncoding.EncodedLen(len(enc))
	base64Enc := make([]byte, base64EncodedLen)
	base64.StdEncoding.Encode(base64Enc, enc)

	err = ioutil.WriteFile(passwdFileName(), base64Enc, os.ModePerm)
	gobro.CheckErr(err)
}
Example #30
0
// Encrypt encrypt the text using a plaintext key
func (a *Aes) Encrypt(text []byte) ([]byte, error) {
	plaintext := []byte(text)
	key := []byte(a.Key)

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	ciphertext := make([]byte, aes.BlockSize+len(plaintext))

	iv := ciphertext[:aes.BlockSize]

	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}

	// Return an encrypted stream
	stream := cipher.NewCFBEncrypter(block, iv)

	// Encrypt bytes from plaintext to ciphertext
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

	return ciphertext, nil
}