Golang crypto-cipher.NewCFBEncrypter类(方法)实例源码

下面列出了Golang crypto-cipher.NewCFBEncrypter 类(方法)源码代码实例,从而了解它的用法。

作者:TykTechnologie    项目:ty   
// 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)
}

作者:jerusalemda    项目:GoTes   
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)
}

作者:JonPulfe    项目:pma   
// 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)
	}
}

作者:st2p    项目:bitcryp   
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
}

作者:TheBauhu    项目:gowebap   
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)
}

作者:tcnks    项目:go-crypt   
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))
}

作者:ylywy    项目:v2ray-cor   
// 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)
}

作者:detailyan    项目:hikaria   
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
}

作者:mohof    项目:CryptoWrappe   
// 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
}

作者:kingfre    项目:hau   
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)
}

作者:fernandop    项目:flashSaf   
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)
}

作者:Herme    项目:herme   
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))
}

作者:dieyush    项目:zzke   
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)
}

作者:NichoZhan    项目:faki   
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
}

作者:melihmucu    项目:mahmu   
// 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
}

作者:richard-lyma    项目:lithcryp   
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
}

作者:haramak    项目:cf   
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
}

作者:duluma    项目:an   
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
}

作者:andradeandre    项目:goadmi   
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
}

作者:cinod    项目:archive-goli   
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
}


问题


面经


文章

微信
公众号

扫码关注公众号