Exemple #1
0
func (c *DBCredentials) buildMasterKey(db *Database) ([]byte, error) {
	masterKey, err := c.buildCompositeKey()
	if err != nil {
		return nil, err
	}

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

	// http://crypto.stackexchange.com/questions/21048/can-i-simulate-iterated-aes-ecb-with-other-block-cipher-modes
	for i := uint64(0); i < db.Headers.TransformRounds; i++ {
		result := make([]byte, 16)
		crypter := cipher.NewCBCEncrypter(block, result)
		crypter.CryptBlocks(masterKey[:16], masterKey[:16])
		crypter = cipher.NewCBCEncrypter(block, result)
		crypter.CryptBlocks(masterKey[16:], masterKey[16:])
	}

	tmp := sha256.Sum256(masterKey)
	masterKey = tmp[:]

	masterKey = append(db.Headers.MasterSeed, masterKey...)
	masterHash := sha256.Sum256(masterKey)
	masterKey = masterHash[:]

	return masterKey, nil
}
Exemple #2
0
func (s *descbc) Sign(algo, usage int, data ...[]byte) ([]byte, error) {
	var h hash.Hash

	switch algo {
	case signGssDes:
		sz := 0
		for _, d := range data {
			sz += len(d)
		}
		sz = (sz + 7) &^ 7
		u := make([]byte, sz)
		v := u[:0]
		for _, d := range data {
			v = append(v, d...)
		}

		iv := [8]byte{}
		b, _ := des.NewCipher(s.key)
		c := cipher.NewCBCEncrypter(b, iv[:])
		c.CryptBlocks(u, u)
		return u[len(u)-8:], nil

	case signGssMd5Des:
		h = md5.New()
		for _, d := range data {
			h.Write(d)
		}
		return s.Sign(signGssDes, usage, h.Sum(nil))

	case signMd5Des:
		h = md5.New()
	case signMd4Des:
		h = md4.New()
	default:
		return unkeyedSign(algo, usage, data...)
	}

	var key [8]byte
	for i := 0; i < 8; i++ {
		key[i] = s.key[i] ^ 0xF0
	}

	chk := make([]byte, 24)
	io.ReadFull(rand.Reader, chk[:8])

	h.Write(chk[:8])
	for _, d := range data {
		h.Write(d)
	}
	h.Sum(chk[8:])

	iv := [8]byte{}
	b, _ := des.NewCipher(s.key)
	c := cipher.NewCBCEncrypter(b, iv[:])
	c.CryptBlocks(chk, chk)
	return chk, nil
}
Exemple #3
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
}
Exemple #4
0
func (t *t_captchaserv) get(w http.ResponseWriter, r *http.Request) {

	defer func() {
		if e := recover(); e != nil {
			fmt.Println(fmt.Errorf("%v", e))
		}
	}()
	if r.Method != "GET" {
		return
	}

	r.ParseForm()
	jsonp := r.FormValue("callback")

	rjson := <-t.iochan
	crypt := make([]byte, 17)
	fmt.Println(rjson.id)

	t.rwmu_chang_state.RLock()
	encrypter := cipher.NewCBCEncrypter(t.bcipher, t.iv[0].val)
	encrypter.CryptBlocks(crypt[1:], []byte(rjson.id))
	crypt[0] = t.iv[0].id
	rjson.id = v_captcha.c.Nodeid + base64.URLEncoding.EncodeToString(crypt)
	t.rwmu_chang_state.RUnlock()

	request := "{\"id\": \"" + rjson.id + "\", \n \"img\": \"" + rjson.img + "\"}"
	if jsonp != "" {
		request = jsonp + "(" + request + ");"
	}

	w.Header().Set("Content-Type", "text/javascript")
	w.Header().Set("Cache-Control", "no-store, no-cache")
	fmt.Fprint(w, request)

}
Exemple #5
0
func ExampleNewCBCEncrypter() {
	key := []byte("example key 1234")
	plaintext := []byte("exampleplaintext")

	// CBC mode works on blocks so plaintexts may need to be padded to the
	// next whole block. For an example of such padding, see
	// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. Here we'll
	// assume that the plaintext is already of the correct length.
	if len(plaintext)%aes.BlockSize != 0 {
		panic("plaintext is not a multiple of the block size")
	}

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

	// 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 {
		panic(err)
	}

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)

	// 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.

	fmt.Printf("%x\n", ciphertext)
}
Exemple #6
0
// ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]
func AESEncryptMsg(random, rawXMLMsg []byte, appId string, aesKey [32]byte) (ciphertext []byte) {
	const (
		BLOCK_SIZE = 32             // PKCS#7
		BLOCK_MASK = BLOCK_SIZE - 1 // BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数
	)

	appIdOffset := 20 + len(rawXMLMsg)
	contentLen := appIdOffset + len(appId)
	amountToPad := BLOCK_SIZE - contentLen&BLOCK_MASK
	plaintextLen := contentLen + amountToPad

	plaintext := make([]byte, plaintextLen)

	// 拼接
	copy(plaintext[:16], random)
	encodeNetworkByteOrder(plaintext[16:20], uint32(len(rawXMLMsg)))
	copy(plaintext[20:], rawXMLMsg)
	copy(plaintext[appIdOffset:], appId)

	// PKCS#7 补位
	for i := contentLen; i < plaintextLen; i++ {
		plaintext[i] = byte(amountToPad)
	}

	// 加密
	block, err := aes.NewCipher(aesKey[:])
	if err != nil {
		panic(err)
	}
	mode := cipher.NewCBCEncrypter(block, aesKey[:16])
	mode.CryptBlocks(plaintext, plaintext)

	ciphertext = plaintext
	return
}
Exemple #7
0
// Encrypt 方法用于对明文进行加密
func (w messageCrypter) encrypt(text string) (string, error) {
	message := []byte(text)

	buf := new(bytes.Buffer)
	if err := binary.Write(buf, binary.BigEndian, int32(len(message))); err != nil {
		return "", err
	}

	msgLen := buf.Bytes()

	randBytes := make([]byte, 16)
	if _, err := io.ReadFull(rand.Reader, randBytes); err != nil {
		return "", err
	}

	messageBytes := bytes.Join([][]byte{randBytes, msgLen, message, []byte(w.appID)}, nil)

	encoded := fillEncode(messageBytes)

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

	cbc := cipher.NewCBCEncrypter(c, w.iv)
	cbc.CryptBlocks(encoded, encoded)

	return base64.StdEncoding.EncodeToString(encoded), nil
}
Exemple #8
0
func TestCBC_AES(t *testing.T) {
	for _, tt := range cbcAESTests {
		test := tt.name

		c, err := aes.NewCipher(tt.key)
		if err != nil {
			t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
			continue
		}

		encrypter := cipher.NewCBCEncrypter(c, tt.iv)
		d := make([]byte, len(tt.in))
		encrypter.CryptBlocks(d, tt.in)
		if !bytes.Equal(tt.out, d) {
			t.Errorf("%s: CBCEncrypter\nhave %x\nwant %x", test, d, tt.out)
		}

		decrypter := cipher.NewCBCDecrypter(c, tt.iv)
		p := make([]byte, len(d))
		decrypter.CryptBlocks(p, d)
		if !bytes.Equal(tt.in, p) {
			t.Errorf("%s: CBCDecrypter\nhave %x\nwant %x", test, d, tt.in)
		}
	}
}
Exemple #9
0
func NewAesCBCCrypter(key []byte, iv []byte) (*AesCBCCrypter, error) {
	l := len(key)
	if l != 32 && l != 24 && l != 16 {
		return nil, errors.New("The key argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.")
	}

	block, _ := aes.NewCipher(key)
	blockSize := block.BlockSize()
	if len(iv) != blockSize {
		return nil, errors.New("The length of iv must be the same as the Block's block size " + strconv.Itoa(blockSize))
	}

	this := &AesCBCCrypter{
		blockSize: blockSize,

		encryptBlockMode: cipher.NewCBCEncrypter(block, iv),
		decryptBlockMode: cipher.NewCBCDecrypter(block, iv),

		padding: &PKCS5Padding{
			BlockSize: blockSize,
		},
	}

	return this, nil
}
Exemple #10
0
func EncryptFilename(filename []byte, key string) (out []byte, err error) {
	// Buffer needs to be multiples of aes.BlockSize
	var buf []byte
	if len(filename)%aes.BlockSize != 0 {
		buf = make([]byte, ((len(filename)/aes.BlockSize)+1)*aes.BlockSize)
		copy(buf, filename)
	} else {
		buf = filename
	}

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

	// sha256 the filename to use as IV
	hash := sha256.New()
	hash.Write(filename)
	salt := hash.Sum(nil)

	if len(salt) < aes.BlockSize {
		panic("Salt too short")
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	out = make([]byte, aes.BlockSize+len(buf))
	iv := out[:aes.BlockSize]
	copy(iv, salt[:aes.BlockSize])

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(out[aes.BlockSize:], buf)

	return out, nil
}
Exemple #11
0
// encrypt tunnel data in place
func (t *Tunnel) Encrypt(td *TunnelData) {
	data := *td
	t.ivKey.Encrypt(data[16:1024], data[16:1024])
	layerBlock := cipher.NewCBCEncrypter(t.layerKey, data[:16])
	layerBlock.CryptBlocks(data[16:1024], data[16:1024])
	t.ivKey.Encrypt(data[16:1024], data[16:1024])
}
Exemple #12
0
func EncryptShimTicket(in []byte) []byte {
	name := TestShimTicketKey[:16]
	macKey := TestShimTicketKey[16:32]
	encKey := TestShimTicketKey[32:48]

	h := hmac.New(sha256.New, macKey)

	block, err := aes.NewCipher(encKey)
	if err != nil {
		panic(err)
	}

	// Use the zero IV for rewritten tickets.
	iv := make([]byte, block.BlockSize())
	cbc := cipher.NewCBCEncrypter(block, iv)
	pad := block.BlockSize() - (len(in) % block.BlockSize())

	out := make([]byte, 0, len(name)+len(iv)+len(in)+pad+h.Size())
	out = append(out, name...)
	out = append(out, iv...)
	out = append(out, in...)
	for i := 0; i < pad; i++ {
		out = append(out, byte(pad))
	}

	ciphertext := out[len(name)+len(iv):]
	cbc.CryptBlocks(ciphertext, ciphertext)

	h.Write(out)
	return h.Sum(out)
}
Exemple #13
0
// Seal fulfills the crypto.AEAD interface
func (c AesCbcHmac) Seal(dst, nonce, plaintext, data []byte) []byte {
	ctlen := len(plaintext)
	ciphertext := make([]byte, ctlen+c.Overhead())[:ctlen]
	copy(ciphertext, plaintext)
	ciphertext = padbuf.PadBuffer(ciphertext).Pad(c.blockCipher.BlockSize())

	cbc := cipher.NewCBCEncrypter(c.blockCipher, nonce)
	cbc.CryptBlocks(ciphertext, ciphertext)

	authtag := c.ComputeAuthTag(data, nonce, ciphertext)

	retlen := len(dst) + len(ciphertext) + len(authtag)

	ret := ensureSize(dst, retlen)
	out := ret[len(dst):]
	n := copy(out, ciphertext)
	n += copy(out[n:], authtag)

	if debug.Enabled {
		debug.Printf("Seal: ciphertext = %x (%d)\n", ciphertext, len(ciphertext))
		debug.Printf("Seal: authtag    = %x (%d)\n", authtag, len(authtag))
		debug.Printf("Seal: ret        = %x (%d)\n", ret, len(ret))
	}
	return ret
}
Exemple #14
0
func (alg *AesCbcHmac) Encrypt(aad, plainText, cek []byte) (iv, cipherText, authTag []byte, err error) {

	cekSizeBits := len(cek) << 3
	if cekSizeBits != alg.keySizeBits {
		return nil, nil, nil, errors.New(fmt.Sprintf("AesCbcHmac.Encrypt(): expected key of size %v bits, but was given %v bits.", alg.keySizeBits, cekSizeBits))
	}

	hmacKey := cek[0 : len(cek)/2]
	aesKey := cek[len(cek)/2:]

	if iv, err = arrays.Random(16); err != nil {
		return nil, nil, nil, err
	}

	var block cipher.Block

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

	padded := padding.AddPkcs7(plainText, 16)

	cipherText = make([]byte, len(padded), cap(padded))
	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(cipherText, padded)

	authTag = alg.computeAuthTag(aad, iv, cipherText, hmacKey)

	return iv, cipherText, authTag, nil
}
Exemple #15
0
func (c *AESCodec) Encrypt(b []byte) (cipherdata []byte, err error) {
	// PKCS#7: padd with n, where n is the number of bytes remaining
	// to reach a multiple of the block size
	l := len(b)

	n := aes.BlockSize - l%aes.BlockSize
	cipherdata = make([]byte, aes.BlockSize+l+n)

	iv := cipherdata[:aes.BlockSize]
	data := cipherdata[aes.BlockSize:]

	copy(data, b)
	for i := 0; i < n; i++ {
		data[l+i] = byte(n)
	}

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

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(cipherdata[aes.BlockSize:], data)

	return
}
Exemple #16
0
func (ak *aesKey) Encrypt(data []byte) ([]byte, error) {
	data = pkcs5pad(data, aes.BlockSize)
	iv := make([]byte, aes.BlockSize)
	io.ReadFull(rand.Reader, iv)
	aesCipher, err := aes.NewCipher(ak.key)
	if err != nil {
		return nil, err
	}
	// aes only ever created with CBC as a mode
	crypter := cipher.NewCBCEncrypter(aesCipher, iv)
	cipherBytes := make([]byte, len(data))
	crypter.CryptBlocks(cipherBytes, data)
	h := makeHeader(ak)
	msg := make([]byte, 0, kzHeaderLength+aes.BlockSize+len(cipherBytes)+hmacSigLength)
	msg = append(msg, h...)
	msg = append(msg, iv...)
	msg = append(msg, cipherBytes...)
	// we sign the header, iv, and ciphertext
	sig, err := ak.hmac.Sign(msg)
	if err != nil {
		return nil, err
	}
	msg = append(msg, sig...)
	return msg, nil
}
Exemple #17
0
func (c LocalCrypter) Encrypt(plaintext string, encryptParams EncryptParams) (Ciphertext, DecryptParams, error) {
	padding := aes.BlockSize - len(plaintext)%aes.BlockSize
	padtext := string(bytes.Repeat([]byte{byte(padding)}, padding))
	plaintext = plaintext + padtext

	key, err := localKey()
	if err != nil {
		return "", nil, fmt.Errorf("Error retrieving local key: %s", err)
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", nil, fmt.Errorf("Error creating AES cipher: %s", err)
	}

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

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], []byte(plaintext))

	b64Ciphertext := base64.StdEncoding.EncodeToString(ciphertext)
	return Ciphertext(b64Ciphertext), nil, nil
}
Exemple #18
0
// AES-CBC 返回binary结果
func AESCBC(byteKey, src []byte, isEncode bool) (rst []byte) {
	rst = make([]byte, len(src))
	b, err := aes.NewCipher(byteKey)
	if err != nil {
		return
	}
	iv := byteKey[:aes.BlockSize]
	var cc cipher.BlockMode
	var nsrc []byte
	if isEncode {
		cc = cipher.NewCBCEncrypter(b, iv)
		nsrc = PKCS5Padding(src, aes.BlockSize)
	} else {
		cc = cipher.NewCBCDecrypter(b, iv)
		nsrc = src
	}
	dst := make([]byte, len(nsrc))
	cc.CryptBlocks(dst, nsrc)
	if isEncode {
		rst = dst
	} else {
		rst = PKCS5UnPadding(dst)
	}
	return
}
Exemple #19
0
// AES256CBCEncrypt encrypts the given plaintext with AES-256 in CBC mode.
// The supplied key must be 32 bytes long.
// The returned ciphertext is prepended by a randomly generated IV.
func AES256CBCEncrypt(key, plaintext []byte, rand io.Reader) (ciphertext []byte) {
	if len(key) != 32 {
		panic(log.Critical("cipher: AES-256 key is not 32 bytes long"))
	}
	block, _ := aes.NewCipher(key) // correct key length was enforced above

	// CBC mode works on blocks so plaintexts may need to be padded to the
	// next whole block. For an example of such padding, see
	// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. Here we'll
	// assume that the plaintext is already of the correct length.
	if len(plaintext)%aes.BlockSize != 0 {
		panic(log.Critical("cipher: plaintext is not a multiple of the block size"))
	}

	// 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]
	_, err := io.ReadFull(rand, iv)
	if err != nil {
		panic(log.Critical(err))
	}

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)

	return
}
Exemple #20
0
func main() {
	plainText := []byte("Bob loves Alice.")
	key := []byte("passw0rdpassw0rdpassw0rdpassw0rd")

	// Create new AES 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))

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

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

	// Decrypt
	decryptedText := make([]byte, len(cipherText[aes.BlockSize:]))
	decryptMode := cipher.NewCBCDecrypter(block, cipherText[:aes.BlockSize])
	decryptMode.CryptBlocks(decryptedText, cipherText[aes.BlockSize:])
	fmt.Printf("Decrypted text: %s\n", string(decryptedText))
}
Exemple #21
0
// Encrypt secures a message using AES-CBC-HMAC-SHA-256 with a random
// nonce.
func Encrypt(key, message []byte) ([]byte, error) {
	if len(key) != KeySize {
		return nil, ErrEncrypt
	}

	iv, err := util.RandBytes(NonceSize)
	if err != nil {
		return nil, ErrEncrypt
	}

	pmessage := pad(message)
	ct := make([]byte, len(pmessage))

	// NewCipher only returns an error with an invalid key size,
	// but the key size was checked at the beginning of the function.
	c, _ := aes.NewCipher(key[:CKeySize])
	ctr := cipher.NewCBCEncrypter(c, iv)
	ctr.CryptBlocks(ct, pmessage)

	h := hmac.New(sha256.New, key[CKeySize:])
	ct = append(iv, ct...)
	h.Write(ct)
	ct = h.Sum(ct)
	return ct, nil
}
Exemple #22
0
func TestInvalidPaddingOpen(t *testing.T) {
	key := make([]byte, 32)
	nonce := make([]byte, 16)

	// Plaintext with invalid padding
	plaintext := padBuffer(make([]byte, 28), aes.BlockSize)
	plaintext[len(plaintext)-1] = 0xFF

	io.ReadFull(rand.Reader, key)
	io.ReadFull(rand.Reader, nonce)

	block, _ := aes.NewCipher(key)
	cbc := cipher.NewCBCEncrypter(block, nonce)
	buffer := append([]byte{}, plaintext...)
	cbc.CryptBlocks(buffer, buffer)

	aead, _ := NewCBCHMAC(key, aes.NewCipher)
	ctx := aead.(*cbcAEAD)

	// Mutated ciphertext, but with correct auth tag
	size := len(buffer)
	ciphertext, tail := resize(buffer, size+(len(key)/2))
	copy(tail, ctx.computeAuthTag(nil, nonce, ciphertext[:size]))

	// Open should fail (b/c of invalid padding, even though tag matches)
	_, err := aead.Open(nil, nonce, ciphertext, nil)
	if err == nil || !strings.Contains(err.Error(), "invalid padding") {
		t.Error("no or unexpected error on open with invalid padding:", err)
	}
}
Exemple #23
0
func CBCEncrypt(key, plaintext []byte) ([]byte, error) {

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

	blockSize := block.BlockSize()

	// CBC mode works on blocks so plaintexts may need to be padded to the
	// next whole block. For an example of such padding, see
	// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. Here we'll
	// assume that the plaintext is already of the correct length.
	r := len(plaintext) % blockSize
	if r != 0 {
		a := make([]byte, blockSize-r)
		plaintext = append(plaintext, a...)
	}
	// 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, blockSize+len(plaintext))
	iv := ciphertext[:blockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[blockSize:], plaintext)

	// 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 ciphertext, nil
}
Exemple #24
0
func add(name string, password []byte) error {
	clipboard.WriteAll(string(password))

	p := Password{}
	p.Salt = randBytes(8)

	key = pbkdf2.Key(key, p.Salt, 4096, 32, sha1.New)

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

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

	mode := cipher.NewCBCEncrypter(session, iv)
	mode.CryptBlocks(pass_ciphered[aes.BlockSize:], password)
	p.Pass = pass_ciphered

	logins[name] = p
	return nil
}
func (c *AESCBCBlockCipher) encrypt(plainText []byte) ([]byte, error) {
	if c.err != nil {
		return nil, c.err
	}

	bs := c.block.BlockSize()

	// pad plainText to an appropriate size
	paddedPlainText, err := pkcs7(plainText, bs)

	if err != nil {
		return nil, err
	}

	if len(paddedPlainText)%bs != 0 {
		return nil, fmt.Errorf("Need a multiple of the blocksize")
	}

	// encrypt
	cipherText := make([]byte, len(paddedPlainText))
	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	// copy(iv[:], cipherText[:bs])

	mode := cipher.NewCBCEncrypter(c.block, c.iv)
	mode.CryptBlocks(cipherText, paddedPlainText)

	return cipherText, nil
}
Exemple #26
0
// Encode encodes the given byte slice and returns a token.
func (tok *T) Encode(data []byte) (token []byte, err error) {
	if data == nil {
		data = []byte{}
	}
	body := make([]byte, 4+len(data))
	now := uint32(time.Now().UTC().Unix())
	binary.BigEndian.PutUint32(body, now)
	copy(body[4:], data)
	body, err = pkcs7Pad(body, aes.BlockSize)
	if err != nil {
		return nil, err
	}
	iv := NewKey(aes.BlockSize)
	mode := cipher.NewCBCEncrypter(tok.aes, iv)
	mode.CryptBlocks(body, body)
	hash := tok.hmac()
	// size = len(iv + aesblocks + signature)
	token = make([]byte, len(iv)+len(body)+hash.Size())
	copy(token, iv)
	offset := len(iv)
	copy(token[offset:], body)
	offset += len(body)
	hash.Write(token[:offset])
	copy(token[offset:], hash.Sum(nil))
	b := make([]byte, base64.RawURLEncoding.EncodedLen(len(token)))
	base64.RawURLEncoding.Encode(b, token)
	return b, nil
}
func (s SecureStorage) encrypt(text []byte, fixedIv bool, inIv string) (string, error) {
	var b string

	block, err := aes.NewCipher(s.secret)
	if err != nil {
		return "", fmt.Errorf("Error during encryption: '%v', %v", err, text)
	}

	data := text
	for {
		b = base64.StdEncoding.EncodeToString(data)
		if len(b)%aes.BlockSize == 0 {
			break
		}
		data = append(data, nullChar)
	}
	ciphertext := make([]byte, aes.BlockSize+len(b))
	iv := ciphertext[:aes.BlockSize]
	if fixedIv == false {
		_, err = io.ReadFull(rand.Reader, iv)
	} else {
		str := inIv + strings.Repeat("a", aes.BlockSize-len(inIv)+10)
		copy(iv, []byte(str)[:aes.BlockSize])
	}
	if err != nil {
		return "", fmt.Errorf("Error during encryption: '%v', %v", err, text)
	}
	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], []byte(b))
	ret := base64.StdEncoding.EncodeToString(ciphertext)
	return ret, nil
}
func cipher3DES(key, iv []byte, isRead bool) interface{} { // 创建3DES算法对称加密
	block, _ := des.NewTripleDESCipher(key)
	if isRead {
		return cipher.NewCBCDecrypter(block, iv)
	}
	return cipher.NewCBCEncrypter(block, iv)
}
Exemple #29
0
func cipherAES(key, iv []byte, isRead bool) interface{} {
	block, _ := aes.NewCipher(key)
	if isRead {
		return cipher.NewCBCDecrypter(block, iv)
	}
	return cipher.NewCBCEncrypter(block, iv)
}
Exemple #30
0
func encrypt(rawValue string) (string, error) {
	if len(encryptionKey) < 1 {
		return "", errors.New("CONFIGO_ENCRYPTION_KEY should be set in order to use `encrypt` function")
	}

	rawBytes := []byte(rawValue)

	if len(rawBytes)%aes.BlockSize != 0 {
		padding := aes.BlockSize - len(rawBytes)%aes.BlockSize
		padtext := bytes.Repeat([]byte{byte(0)}, padding)
		rawBytes = append(rawBytes, padtext...)
	}

	block, err := aes.NewCipher([]byte(encryptionKey))
	if err != nil {
		return "", err
	}
	ciphertext := make([]byte, aes.BlockSize+len(rawBytes))

	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return "", err
	}
	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], rawBytes)

	return base64.StdEncoding.EncodeToString(ciphertext), nil
}