當前位置: 首頁>>代碼示例>>Golang>>正文


Golang cipher.NewCBCDecrypter函數代碼示例

本文整理匯總了Golang中crypto/cipher.NewCBCDecrypter函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewCBCDecrypter函數的具體用法?Golang NewCBCDecrypter怎麽用?Golang NewCBCDecrypter使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewCBCDecrypter函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: GosaDecryptBuffer

// Like GosaDecrypt() but operates in-place on buf.
// Returns true if decryption successful and false if not.
// If false is returned, the buffer contents may be destroyed, but only
// if further decryption attempts with other keys would be pointless anyway,
// because of some fatal condition (such as the data not being a multiple of
// the cipher's block size).
func GosaDecryptBuffer(buf *bytes.Buffer, key string) bool {
	buf.TrimSpace()

	if buf.Len() < 11 {
		return false
	} // minimum length of unencrypted <xml></xml>

	data := buf.Bytes()
	if string(data[0:5]) == "<xml>" {
		return true
	}

	// Fixes the following:
	// * gosa-si bug in the following line:
	//     if( $client_answer =~ s/session_id=(\d+)$// ) {
	//   This leaves the "." before "session_id" which breaks base64
	// * new gosa-si protocol has ";IP:PORT" appended to message
	//   which also breaks base64
	for semicolon_period := 0; semicolon_period < len(data); semicolon_period++ {
		if data[semicolon_period] == ';' || data[semicolon_period] == '.' {
			buf.Trim(0, semicolon_period)
			data = buf.Bytes()
			break
		}
	}

	aescipher, _ := aes.NewCipher([]byte(util.Md5sum(key)))
	crypter := cipher.NewCBCDecrypter(aescipher, config.InitializationVector)

	cryptotest := make([]byte, (((3*aes.BlockSize)+2)/3)<<2)
	n := copy(cryptotest, data)
	cryptotest = cryptotest[0:n]
	cryptotest = util.Base64DecodeInPlace(cryptotest)
	n = (len(cryptotest) / aes.BlockSize) * aes.BlockSize
	cryptotest = cryptotest[0:n]
	crypter.CryptBlocks(cryptotest, cryptotest)
	if !strings.Contains(string(cryptotest), "<xml>") {
		return false
	}

	data = util.Base64DecodeInPlace(data)
	buf.Trim(0, len(data))
	data = buf.Bytes()

	if buf.Len()%aes.BlockSize != 0 {
		// this condition is fatal => further decryption attempts are pointless
		buf.Reset()
		return false
	}

	crypter = cipher.NewCBCDecrypter(aescipher, config.InitializationVector)
	crypter.CryptBlocks(data, data)

	buf.TrimSpace() // removes 0 padding, too

	return true
}
開發者ID:chrlutz,項目名稱:limux-gosa,代碼行數:63,代碼來源:gosacrypt.go

示例2: DecryptFile

func DecryptFile(filepath string, key []byte) {

	fmt.Println()

	cipherText, err := os.Open(filepath)
	if err != nil {
		fmt.Println("ERROR:", err)
	}
	defer cipherText.Close()

	plainText, err := os.Create(filepath + ".dec")
	if err != nil {
		fmt.Println("ERROR:", err)
	}
	defer plainText.Close()

	iv := make([]byte, 16) //AES const

	_, err = cipherText.Read(iv)
	fmt.Println("iv=", iv[:])
	if err != nil {
		fmt.Println("ERROR:", err)
	}

	encBlock := make([]byte, 16) // AES const
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println("ERROR:", err)
	}

	mode := cipher.NewCBCDecrypter(block, iv)
	// we have decrypter, can loop over file contents now

	// know size so can not get EOF'd
	stats, err := cipherText.Stat()
	if err != nil {
		fmt.Println("ERROR:", err)
	}
	var ReadAmt int64 = 16
	message := make([]byte, 16)

	for ReadAmt != stats.Size() {
		//read in file, decrypt, check for end, if so strip padding
		if _, err := cipherText.Read(encBlock); err != nil {
			fmt.Println("ERROR:", err)
		}

		ReadAmt += 16 // AES const
		mode.CryptBlocks(message, encBlock)

		//check for end, if so strip pad
		fmt.Println("encrypt=", encBlock[:])
		fmt.Println("message=", message[:])
		if ReadAmt == stats.Size() {
			pad := message[15]
			message = message[:16-pad]
		}
		plainText.Write(message)
	}
}
開發者ID:postfix,項目名稱:secureBox,代碼行數:60,代碼來源:encryption.go

示例3: cipherAES

func cipherAES(key, iv []byte, isRead bool) interface{} {
	block, _ := aes.NewCipher(key)
	if isRead {
		return cipher.NewCBCDecrypter(block, iv)
	}
	return cipher.NewCBCEncrypter(block, iv)
}
開發者ID:randombit,項目名稱:hacrypto,代碼行數:7,代碼來源:cipher_suites.go

示例4: Open

// Open decrypts and authenticates the ciphertext.
func (ctx *cbcAEAD) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
	if len(ciphertext) < ctx.authtagBytes {
		return nil, errors.New("square/go-jose: invalid ciphertext (too short)")
	}

	offset := len(ciphertext) - ctx.authtagBytes
	expectedTag := ctx.computeAuthTag(data, nonce, ciphertext[:offset])
	match := subtle.ConstantTimeCompare(expectedTag, ciphertext[offset:])
	if match != 1 {
		return nil, errors.New("square/go-jose: invalid ciphertext (auth tag mismatch)")
	}

	cbc := cipher.NewCBCDecrypter(ctx.blockCipher, nonce)

	// Make copy of ciphertext buffer, don't want to modify in place
	buffer := append([]byte{}, []byte(ciphertext[:offset])...)

	if len(buffer)%ctx.blockCipher.BlockSize() > 0 {
		return nil, errors.New("square/go-jose: invalid ciphertext (invalid length)")
	}

	cbc.CryptBlocks(buffer, buffer)

	// Remove padding
	plaintext, err := unpadBuffer(buffer, ctx.blockCipher.BlockSize())
	if err != nil {
		return nil, err
	}

	ret, out := resize(dst, len(dst)+len(plaintext))
	copy(out, plaintext)

	return ret, nil
}
開發者ID:CowLeo,項目名稱:distribution,代碼行數:35,代碼來源:cbc_hmac.go

示例5: decrypt

func (s SecureStorage) decrypt(text1 []byte) (string, error) {
	var data []byte

	// The decrypt may be called with un-encrypted data (the hash key to random,
	//   may be OK in some cases thus thiis has to be verified by the caller)
	defer func() (string, error) {
		if r := recover(); r != nil {
			return "", fmt.Errorf("during decryption: '%v'", text1)
		}
		return string(data), nil
	}()

	text, err := base64.StdEncoding.DecodeString(string(text1))
	if err != nil {
		return "", fmt.Errorf("during decryption: '%v', error: %v", text, err)
	}

	block, err := aes.NewCipher(s.secret)
	if err != nil {
		return "", fmt.Errorf("during decryption: '%v', error: %v", text, err)
	}
	if len(text) < aes.BlockSize {
		return "", fmt.Errorf("Error during decryption: Ciphertext too short")
	}
	iv := text[:aes.BlockSize]
	dtext := text[aes.BlockSize:]
	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(dtext, dtext)
	return string(dtext), nil
}
開發者ID:ibm-security-innovation,項目名稱:libsecurity-go,代碼行數:30,代碼來源:secureStorage.go

示例6: decrypt

func (c *AESCBCBlockCipher) decrypt(cipherText []byte) ([]byte, error) {
	if c.err != nil {
		return nil, c.err
	}

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

	mode := cipher.NewCBCDecrypter(c.block, c.iv)

	// CryptBlocks can work in-place if the two arguments are the same.
	mode.CryptBlocks(cipherText, cipherText)

	// If the original plainText lengths are not a multiple of the block
	// size, padding would have to be added when encrypting, which would be
	// removed at this point. For an example, see
	// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. However, it's
	// critical to note that cipherTexts must be authenticated (i.e. by
	// using crypto/hmac) before being decrypted in order to avoid creating
	// a padding oracle.

	return stripPadding(cipherText), nil
}
開發者ID:jabley,項目名稱:matasano-crypto-challenges,代碼行數:25,代碼來源:aes.go

示例7: Decrypt

func (s *descbc) Decrypt(salt []byte, algo, usage int, data []byte) ([]byte, error) {
	var h hash.Hash

	switch algo {
	case cryptDesCbcMd5:
		h = md5.New()
	case cryptDesCbcMd4:
		h = md4.New()
	default:
		return nil, ErrProtocol
	}

	if (len(data) & 7) != 0 {
		return nil, ErrProtocol
	}

	iv := [8]byte{}
	b, _ := des.NewCipher(s.key)
	c := cipher.NewCBCDecrypter(b, iv[:])
	c.CryptBlocks(data, data)

	chk := make([]byte, h.Size())
	h.Write(data[:8])
	h.Write(chk) // Just need h.Size() zero bytes instead of the checksum
	h.Write(data[8+len(chk):])
	h.Sum(chk[:0])

	if subtle.ConstantTimeCompare(chk, data[8:8+len(chk)]) != 1 {
		return nil, ErrProtocol
	}

	return data[8+len(chk):], nil
}
開發者ID:JFHSebastian,項目名稱:gokerb,代碼行數:33,代碼來源:crypto.go

示例8: Decrypt

// Takes json string
func Decrypt(s string, password string) (string, error) {
	var obj Crypto
	if err := json.Unmarshal([]byte(s), &obj); err != nil {
		return "", err
	}

	iv, err := base64.StdEncoding.DecodeString(obj.Iv)
	if err != nil {
		return "", err
	}

	salt, err := base64.StdEncoding.DecodeString(obj.Salt)
	if err != nil {
		return "", err
	}

	ct, err := base64.StdEncoding.DecodeString(obj.Ct)
	if err != nil {
		return "", err
	}

	key := buildDecryptionKey(password, string(salt))

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

	decrypter := cipher.NewCBCDecrypter(block, iv)
	data := make([]byte, len(ct))
	decrypter.CryptBlocks(data, ct)

	return string(data), nil
}
開發者ID:rendom,項目名稱:vvt-cli,代碼行數:35,代碼來源:cryptojs.go

示例9: AES256CBCDecrypt

// AES256CBCDecrypt decrypts the given ciphertext with AES-256 in CBC mode and
// returns the resulting plaintext. The supplied key must be 32 bytes long and
// the ciphertext must be prepended by the corresponding IV.
func AES256CBCDecrypt(key, ciphertext []byte) (plaintext []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

	// 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 {
		panic(log.Critical("cipher: ciphertext too short"))
	}
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]
	plaintext = make([]byte, len(ciphertext))

	// CBC mode always works in whole blocks.
	if len(ciphertext)%aes.BlockSize != 0 {
		panic(log.Critical("cipher: ciphertext is not a multiple of the block size"))
	}

	mode := cipher.NewCBCDecrypter(block, iv)

	// CryptBlocks can work in-place if the two arguments are the same.
	mode.CryptBlocks(plaintext, ciphertext)

	return
}
開發者ID:JonathanLogan,項目名稱:mute,代碼行數:30,代碼來源:aes256.go

示例10: Decrypt

// Decrypt decrypts the provided ciphertext, reversing the Encrypt method.
func Decrypt(ciphertext []byte, passphrase string) []byte {
	key := makeKeySlice(passphrase)

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

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

	if len(ciphertext)%aes.BlockSize != 0 {
		panic("ciphertext is not a multiple of the block size")
	}

	mode := cipher.NewCBCDecrypter(block, iv)

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

	padLength := int(uint8(ciphertext[len(ciphertext)-1]))
	unpadded := ciphertext[:len(ciphertext)-padLength]

	return unpadded
}
開發者ID:jcnnghm,項目名稱:cmdtrack,代碼行數:26,代碼來源:encrypt.go

示例11: NewAesCBCCrypter

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
}
開發者ID:Andals,項目名稱:gobox,代碼行數:25,代碼來源:aes.go

示例12: Decrypt

func (c LocalCrypter) Decrypt(b64ciphertext Ciphertext, decryptParams DecryptParams) (string, error) {
	key, err := localKey()
	if err != nil {
		return "", fmt.Errorf("Error retrieving local key: %s", err)
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", fmt.Errorf("Error creating AES cipher: %s", err)
	}

	ciphertext, err := base64.StdEncoding.DecodeString(string(b64ciphertext))
	if err != nil {
		return "", fmt.Errorf("Ciphertext is not valid base64 encoded in secret '%s'", b64ciphertext)
	}
	if len(ciphertext) < aes.BlockSize {
		return "", fmt.Errorf("Ciphertext too short in secret '%s'", ciphertext)
	}
	iv := []byte(ciphertext[:aes.BlockSize])
	ciphertext = ciphertext[aes.BlockSize:]

	if len(ciphertext)%aes.BlockSize != 0 {
		return "", fmt.Errorf("Ciphertext is not a multiple of the block size in secret '%s'", ciphertext)
	}

	mode := cipher.NewCBCDecrypter(block, iv)

	plaintext := make([]byte, len(ciphertext))
	mode.CryptBlocks(plaintext, []byte(ciphertext))

	length := len(plaintext)
	unpadding := int(plaintext[length-1])
	plaintext = plaintext[:(length - unpadding)]
	return string(plaintext), nil
}
開發者ID:Zemanta,項目名稱:go-secretcrypt,代碼行數:34,代碼來源:local.go

示例13: PlainText

// Get the plain text out of a frame
func (fr *Frame) PlainText() []DIFs {
	if fr.Key != "" {
		// Check whether the encrypted value is too long, if this is the case it is
		// a plaintext extension and we have to parse this data
		if (len(fr.Value[fr.ValueStart()*2:]) / 2) > fr.ConfigurationLength() {
			return getDIFs(fr.Value[fr.ValueStart()*2+fr.ConfigurationLength()*2:])
		}

		//if(fr.ValueStart()+fr.ConfigurationLength())*2
		key, err := hex.DecodeString(fr.Key)
		if err == nil {
			ciphertext, err := hex.DecodeString(fr.Value[fr.ValueStart()*2:])
			if err == nil {
				block, err := aes.NewCipher(key)
				if err == nil {
					iv, err := hex.DecodeString(fr.IV())
					if err == nil {
						mode := cipher.NewCBCDecrypter(block, iv)
						mode.CryptBlocks(ciphertext, ciphertext)
						plaintext := fmt.Sprintf("%s\n", hex.EncodeToString(ciphertext))
						values := getDIFs(plaintext)
						return values
					}
				}
			}
		}
	}
	return nil
}
開發者ID:CompassSecurity,項目名稱:WMBus-Sniffer-MUC,代碼行數:30,代碼來源:decrypt.go

示例14: cipher3DES

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)
}
開發者ID:Maplecms,項目名稱:golang1.5-src,代碼行數:7,代碼來源:cipher_suites.go

示例15: Decode

// Decode decodes the given token and return its data
// and creation time in UTC.
func (tok *T) Decode(token []byte) (data []byte, creation time.Time, err error) {
	raw := make([]byte, base64.RawURLEncoding.DecodedLen(len(token)))
	n, err := base64.RawURLEncoding.Decode(raw, token)
	if err != nil {
		return nil, time.Time{}, err
	}
	raw = raw[:n]
	hash := tok.hmac()
	if len(raw) < aes.BlockSize*2+hash.Size() {
		return nil, time.Time{}, ErrInvalidToken
	}
	soff := len(raw) - hash.Size() // signature offset
	hash.Write(raw[:soff])
	want := hash.Sum(nil)
	have := raw[soff:]
	if !hmac.Equal(want, have) {
		return nil, time.Time{}, ErrInvalidTokenSignature
	}
	iv := raw[:aes.BlockSize]
	body := raw[aes.BlockSize:soff]
	if len(body)%aes.BlockSize != 0 {
		return nil, time.Time{}, ErrInvalidToken
	}
	mode := cipher.NewCBCDecrypter(tok.aes, iv)
	mode.CryptBlocks(body, body)
	ts := time.Unix(int64(binary.BigEndian.Uint32(body)), 0)
	body, err = pkcs7Unpad(body, aes.BlockSize)
	if err != nil {
		return nil, time.Time{}, err
	}
	return body[4:], ts.UTC(), nil
}
開發者ID:go-web,項目名稱:tokenizer,代碼行數:34,代碼來源:token.go


注:本文中的crypto/cipher.NewCBCDecrypter函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。