本文整理汇总了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
}
示例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)
}
}
示例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)
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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)
}
示例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
}