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

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

作者:traeto    项目:blogEngin   
func DecodePostPush(nbpp *PostPush, seed int64, passbytes []byte) (PostContent, error) {
	var nbpc PostContent
	bb := bytes.NewBuffer(nbpp.Content)

	//get hash generated
	res := hashIt(seed, passbytes)

	//get our encrypter rolling
	block, err := aes.NewCipher(res)
	if err != nil {
		return nbpc, err
	}
	stream := cipher.NewCFBDecrypter(block, nbpp.IV)
	cryptrdr := cipher.StreamReader{S: stream, R: bb}

	dec := gob.NewDecoder(cryptrdr)
	if err := dec.Decode(&nbpc); err != nil {
		return nbpc, err
	}

	//verify hash
	if !CompareHash(nbpc.BP.hash(), nbpc.Hash) {
		return nbpc, errors.New("Invalid post hash")
	}

	return nbpc, nil
}

作者:st2p    项目:bitcryp   
func AesDecryptFd(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.NewCFBDecrypter(block, iv[:])
	case 2:
		stream = cipher.NewCTR(block, iv[:])
	default:
		stream = cipher.NewOFB(block, iv[:])
	}

	reader := &cipher.StreamReader{S: stream, R: inFile}
	// Copy the input file to the output file, decrypting as we go.
	if _, err := io.Copy(outFile, reader); 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 output.
	return nil
}

作者:JayBlaze42    项目:camlistor   
// Decrypt attempts to decrypt an encrypted session key. If it returns nil,
// ske.Key will contain the session key.
func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) error {
	if !ske.Encrypted {
		return nil
	}

	key := make([]byte, ske.CipherFunc.KeySize())
	ske.s2k(key, passphrase)

	if len(ske.encryptedKey) == 0 {
		ske.Key = key
	} else {
		// the IV is all zeros
		iv := make([]byte, ske.CipherFunc.blockSize())
		c := cipher.NewCFBDecrypter(ske.CipherFunc.new(key), iv)
		c.XORKeyStream(ske.encryptedKey, ske.encryptedKey)
		ske.CipherFunc = CipherFunction(ske.encryptedKey[0])
		if ske.CipherFunc.blockSize() == 0 {
			return errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(ske.CipherFunc)))
		}
		ske.CipherFunc = CipherFunction(ske.encryptedKey[0])
		ske.Key = ske.encryptedKey[1:]
		if len(ske.Key)%ske.CipherFunc.blockSize() != 0 {
			ske.Key = nil
			return errors.StructuralError("length of decrypted key not a multiple of block size")
		}
	}

	ske.Encrypted = false
	return nil
}

作者:krionu    项目:goploade   
func view(c *gin.Context) {
	id := c.Param("uniuri")
	key := c.Param("key")
	re := models.ResourceEntry{}
	remote := c.ClientIP()

	db.Where(&models.ResourceEntry{Key: id}).First(&re)
	if re.Key == "" {
		log.Printf("[INFO][%s]\tNot found : %s", remote, id)
		c.AbortWithStatus(http.StatusNotFound)
		return
	}
	log.Printf("[INFO][%s]\tFetched %s file and entry\n", remote, id)
	f, err := os.Open(path.Join(conf.C.UploadDir, re.Key))
	if err != nil {
		log.Printf("[ERROR][%s]\tWhile opening %s file\n", remote, id)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		log.Printf("[ERROR][%s]\tDuring Cipher creation : %s\n", remote, err)
		c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	var iv [aes.BlockSize]byte
	stream := cipher.NewCFBDecrypter(block, iv[:])
	reader := &cipher.StreamReader{S: stream, R: f}
	c.Header("Content-Disposition", "filename=\""+re.Name+"\"")
	io.Copy(c.Writer, reader)
}

作者:cubee    项目:go-si   
func decrypt(str string) (plaintext string, err error) {
	ciphertext, err := hex.DecodeString(str)
	if err != nil {
		return "", err
	}

	var block cipher.Block
	if block, err = aes.NewCipher(AES_KEY); err != nil {
		return
	}

	if len(ciphertext) < aes.BlockSize {
		err = errors.New("ciphertext too short")
		return
	}

	iv := ciphertext[:aes.BlockSize]
	fmt.Println(iv)
	ciphertext = ciphertext[aes.BlockSize:]

	cfb := cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(ciphertext, ciphertext)

	plaintext = string(ciphertext)
	return
}

作者:kobel    项目:goutil   
// Eecrypt from base64 to decrypted string
func Decrypt(keyStr, cryptoText string) (r string, err error) {
	key := []byte(keyStr)
	ciphertext, err := base64.URLEncoding.DecodeString(cryptoText)
	if err != nil {
		return
	}

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

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	if len(ciphertext) < aes.BlockSize {
		err = errors.New("ciphertext too short")
		return
	}

	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

	stream := cipher.NewCFBDecrypter(block, iv)

	// XORKeyStream can work in-place if the two arguments are the same.
	stream.XORKeyStream(ciphertext, ciphertext)

	r = fmt.Sprintf("%s", ciphertext)
	return
}

作者:andradeandre    项目:goadmi   
func Decrypt(key string, publickey PublicKey, rin io.Reader) (r io.Reader, length int64, sequence int64, e os.Error) {
	c, e := simpleCipher(key)
	if e != nil {
		e = os.NewError("Trouble reading the symmetric key: " + e.String())
		return
	}
	pub, e := readPublicKey(publickey)
	if e != nil {
		e = os.NewError("Trouble reading the public key: " + e.String())
		return
	}
	iv := make([]byte, c.BlockSize())
	_, e = io.ReadFull(rin, iv) // read the iv first (it's not encrypted)
	if e != nil {
		e = os.NewError("Trouble reading the iv: " + e.String())
		return
	}
	decrypter := cipher.NewCFBDecrypter(c, iv)
	rdec := flate.NewReader(cipher.StreamReader{decrypter, rin})
	e = binary.Read(rdec, binary.LittleEndian, &length)
	if e != nil {
		e = os.NewError("Trouble reading the file length: " + e.String())
		return
	}
	e = binary.Read(rdec, binary.LittleEndian, &sequence)
	if e != nil {
		e = os.NewError("Trouble reading the serial number: " + e.String())
		return
	}
	return &hashReader{rdec, sha256.New(), pub, length}, length, sequence, nil
}

作者:mohof    项目:CryptoWrappe   
// decryptAES derypts ciphertext input with passed key and mode (IV is contained in input)
// in AES block cipher; and returns plaintext output
func decryptAES(input []byte, output []byte, key []byte, mode Mode) error {
	block, err := aes.NewCipher(key)
	if err != nil {
		return errors.New("Couldn't create block cipher.")
	}
	if len(input) < aes.BlockSize {
		return errors.New("Ciphertext too short.")
	}

	iv := input[:aes.BlockSize]
	ciphertext := input[aes.BlockSize:]

	switch mode {
	case CBC:
		if len(input)%aes.BlockSize != 0 {
			return errors.New("Ciphertext doesn't satisfy CBC-mode requirements.")
		}
		mode := cipher.NewCBCDecrypter(block, iv)
		mode.CryptBlocks(output, ciphertext)
	case CFB:
		mode := cipher.NewCFBDecrypter(block, iv)
		mode.XORKeyStream(output, ciphertext)
	case CTR:
		mode := cipher.NewCTR(block, iv)
		mode.XORKeyStream(output, ciphertext)
	case OFB:
		mode := cipher.NewOFB(block, iv)
		mode.XORKeyStream(output, ciphertext)
	}
	return nil
}

作者:duluma    项目:an   
func AESDecrypt(c string, key string) (s string, err error) {
	var k []byte
	var block cipher.Block
	var cfb cipher.Stream
	var cb []byte
	var iv []byte

	k = AESMake256Key(key)

	cb, err = hex.DecodeString(c)
	if err != nil {
		return
	}

	block, err = aes.NewCipher(k)
	if err != nil {
		return
	}
	if len(cb) < aes.BlockSize {
		err = errors.New("crypt string is too short")
		return
	}

	iv = cb[:aes.BlockSize]
	cb = cb[aes.BlockSize:]

	cfb = cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(cb, cb)
	s = bytes.NewBuffer(cb).String()
	return
}

作者:fernandop    项目:flashSaf   
func decryptFile(path string) {
	fmt.Printf("UnLock: %s\n", path)

	content, 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)
	}

	iv := content[:aes.BlockSize]
	cyphertext := content[aes.BlockSize:]

	plaintext := make([]byte, len(content)-aes.BlockSize)

	stream := cipher.NewCFBDecrypter(block, iv)
	stream.XORKeyStream(plaintext, cyphertext)

	f, err := os.Create(path[:len(path)-4])
	if err != nil {
		panic(err.Error())
	}
	_, err = io.Copy(f, bytes.NewReader(plaintext))
	if err != nil {
		panic(err.Error())
	}
	os.Remove(path)
}

作者: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
}

作者: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)
}

作者:Herme    项目:herme   
func Decrypt(in io.Reader, key string) io.Reader {

	buf := new(bytes.Buffer)
	buf.ReadFrom(in)
	s := buf.String()

	// Load the ciphertext message you want to decrypt
	ciphertext := []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 CFBDecrypter in order to decrypt
	// the whole stream of ciphertext using the
	// cipher setup with c and a iv.
	cfb := cipher.NewCFBDecrypter(c, commonIV)
	plaintext := make([]byte, len(ciphertext))
	cfb.XORKeyStream(plaintext, ciphertext)
	return strings.NewReader(string(plaintext))
}

作者: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
}

作者:dieuca    项目:notification   
// Unveil base64 decodes a slice of bytes and uses aes encryption to decrypt. It returns a decrypted slice of bytes,
// and an error. A CipherLengthError is returned if the data is less than 16 bytes.
func (cloak Cloak) Unveil(data []byte) ([]byte, error) {
	decodedData := make([]byte, base64.URLEncoding.DecodedLen(len(data)))
	n, err := base64.URLEncoding.Decode(decodedData, data)
	if err != nil {
		return []byte{}, err
	}
	decodedData = decodedData[:n]

	if len(decodedData) < aes.BlockSize {
		return []byte{}, CipherLengthError{}
	}

	initializationVector := decodedData[:aes.BlockSize]
	decodedData = decodedData[aes.BlockSize:]

	cipherDecrypter := cipher.NewCFBDecrypter(cloak.cipherBlock, initializationVector)
	cipherDecrypter.XORKeyStream(decodedData, decodedData)

	decoded := make([]byte, base64.StdEncoding.DecodedLen(len(decodedData)))
	n, err = base64.StdEncoding.Decode(decoded, decodedData)
	if err != nil {
		return []byte{}, err
	}

	return decoded[:n], nil
}

作者:cinod    项目:archive-goli   
func createDecryptorAES256(key []byte, ivSource []byte, input io.Reader) (reader io.Reader, err error) {

	if len(key) != 32 {
		return nil, ErrInvalidKey
	}

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

	// Create new base cipher
	blobCipher, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	// Generate the reader in CFB mode
	return &cipher.StreamReader{
			S: cipher.NewCFBDecrypter(
				blobCipher,
				iv[:]),
			R: input},
		nil
}

作者:s75255091    项目:v2ray-cor   
func ReadVMessUDP(buffer []byte, userset user.UserSet) (*VMessUDP, error) {
	userHash := buffer[:user.IDBytesLen]
	userId, timeSec, valid := userset.GetUser(userHash)
	if !valid {
		return nil, errors.NewAuthenticationError(userHash)
	}

	buffer = buffer[user.IDBytesLen:]
	aesCipher, err := aes.NewCipher(userId.CmdKey())
	if err != nil {
		return nil, err
	}
	aesStream := cipher.NewCFBDecrypter(aesCipher, user.Int64Hash(timeSec))
	aesStream.XORKeyStream(buffer, buffer)

	fnvHash := binary.BigEndian.Uint32(buffer[:4])
	fnv1a := fnv.New32a()
	fnv1a.Write(buffer[4:])
	fnvHashActual := fnv1a.Sum32()

	if fnvHash != fnvHashActual {
		log.Warning("Unexpected fhv hash %d, should be %d", fnvHashActual, fnvHash)
		return nil, errors.NewCorruptedPacketError()
	}

	buffer = buffer[4:]

	vmess := &VMessUDP{
		user:    *userId,
		version: buffer[0],
		token:   binary.BigEndian.Uint16(buffer[1:3]),
	}

	// buffer[3] is reserved

	port := binary.BigEndian.Uint16(buffer[4:6])
	addrType := buffer[6]
	var address v2net.Address
	switch addrType {
	case addrTypeIPv4:
		address = v2net.IPAddress(buffer[7:11], port)
		buffer = buffer[11:]
	case addrTypeIPv6:
		address = v2net.IPAddress(buffer[7:23], port)
		buffer = buffer[23:]
	case addrTypeDomain:
		domainLength := buffer[7]
		domain := string(buffer[8 : 8+domainLength])
		address = v2net.DomainAddress(domain, port)
		buffer = buffer[8+domainLength:]
	default:
		log.Warning("Unexpected address type %d", addrType)
		return nil, errors.NewCorruptedPacketError()
	}

	vmess.address = address
	vmess.data = buffer

	return vmess, nil
}

作者:applepi-icp    项目:icaru   
func Decrypt(content string, orig []byte) (string, error) {
	rawContent, err := base64.StdEncoding.DecodeString(content)
	if err != nil {
		return "", err
	}

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

	// As cipher is random, IV is out of use.
	iv := make([]byte, block.BlockSize())
	stream := cipher.NewCFBDecrypter(block, iv)

	res := make([]byte, len(rawContent))
	stream.XORKeyStream(res, rawContent)

	l := len(res) - ShaLength
	if l < 0 {
		return "", ErrValidation
	}

	s := sha1.New()
	v := s.Sum(res[:l])[:ShaLength]
	if !bytes.Equal(v, res[l:]) {
		return "", ErrValidation
	}

	return string(res[:l]), nil
}

作者: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))
}

作者:bonl    项目:exercis   
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)
}


问题


面经


文章

微信
公众号

扫码关注公众号