本文整理汇总了Golang中crypto/cipher.NewCBCDecrypter函数的典型用法代码示例。如果您正苦于以下问题:Golang NewCBCDecrypter函数的具体用法?Golang NewCBCDecrypter怎么用?Golang NewCBCDecrypter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewCBCDecrypter函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: decrypt
// Decrypt 方法用于对密文进行解密
//
// 返回解密后的消息,CropId/AppId, 或者错误信息
func (w messageCrypter) decrypt(text string) ([]byte, string, error) {
var msgDecrypt []byte
var id string
deciphered, err := base64.StdEncoding.DecodeString(text)
if err != nil {
return nil, "", err
}
c, err := aes.NewCipher(w.key)
if err != nil {
return nil, "", err
}
cbc := cipher.NewCBCDecrypter(c, w.iv)
cbc.CryptBlocks(deciphered, deciphered)
decoded := delDecode(deciphered)
buf := bytes.NewBuffer(decoded[16:20])
var msgLen int32
binary.Read(buf, binary.BigEndian, &msgLen)
msgDecrypt = decoded[20 : 20+msgLen]
id = string(decoded[20+msgLen:])
return msgDecrypt, id, nil
}
开发者ID:trigrass2,项目名称:wechat_component,代码行数:32,代码来源:cipher.go
示例17: decryptData
func decryptData(secret_key []byte, encrypted_data []byte) (string, error) {
block, err := aes.NewCipher(secret_key)
if err != nil {
return "", err
}
if len(encrypted_data) < aes.BlockSize {
return "", errors.New("encrypted data is less than BlockSize")
}
iv := encrypted_data[:aes.BlockSize]
data := encrypted_data[aes.BlockSize:]
if len(data)%aes.BlockSize != 0 {
return "", errors.New("encrypted data is not a multiple of block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(data, data)
// remove padding
trimmed_data := strings.TrimRight(string(data), "=")
return trimmed_data, nil
}
开发者ID:agdt3,项目名称:gosessioncookie,代码行数:26,代码来源:cookie.go
示例18: version1Decoder
func version1Decoder(key []byte, iv, encryptedData string) (interface{}, error) {
ciphertext := decodeBase64(encryptedData)
initVector := decodeBase64(iv)
keySha := sha256.Sum256(key)
block, err := aes.NewCipher(keySha[:])
if err != nil {
return nil, err
}
if len(ciphertext)%aes.BlockSize != 0 {
return nil, errors.New("Ciphertext is wrong length")
}
mode := cipher.NewCBCDecrypter(block, initVector)
mode.CryptBlocks(ciphertext, ciphertext)
ciphertext = unPKCS7Padding(ciphertext)
var item version1Item
_ = json.Unmarshal(ciphertext, &item)
if item.Content == nil {
return nil, fmt.Errorf("Decryption failed, check your decryption key.")
}
return item.Content, nil
}
开发者ID:conjurinc,项目名称:summon-chefapi,代码行数:28,代码来源:decode.go
示例19: NewReader
// Returns a new Reader that reads from r
//
// The header section storing the salt and keys is read from r to verify the file is
// actually a psafe3 file and the password is correct.
//
// All reads from this reader will return unencrypted data.
func NewReader(r io.Reader, password string) (*Reader, error) {
reader := &Reader{r: r, password: password}
var header psv3Header
binary.Read(r, binary.LittleEndian, &header)
if string(header.Tag[:]) != "PWS3" {
return nil, ErrBadFileType
}
sk := computeStretchKey(header.Salt[:], []byte(password), int(header.Iter))
hashsk := sha256.Sum256(sk)
if hashsk != header.HashPPrime {
return nil, ErrInvalidPassword
}
var key, hmacKey [32]byte
tfish, _ := twofish.NewCipher(sk)
tfish.Decrypt(key[:16], header.B1[:])
tfish.Decrypt(key[16:], header.B2[:])
tfish.Decrypt(hmacKey[:16], header.B3[:])
tfish.Decrypt(hmacKey[16:], header.B4[:])
tfish, _ = twofish.NewCipher(key[:])
reader.tfishDecrypter = cipher.NewCBCDecrypter(tfish, header.IV[:])
reader.hmacHash = hmac.New(sha256.New, hmacKey[:])
return reader, nil
}
开发者ID:heatxsink,项目名称:pwsafe,代码行数:35,代码来源:reader.go
示例20: TestCBC_AES
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)
}
}
}
开发者ID:kostyll,项目名称:gccpy,代码行数:25,代码来源:cbc_aes_test.go
注:本文中的crypto/cipher.NewCBCDecrypter函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论