コード例 #1
0
ファイル: blogpost.go プロジェクト: traetox/blogEngine
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
}
コード例 #2
0
ファイル: ut_aes.go プロジェクト: st2py/bitcrypt
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
}
コード例 #3
0
// 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
}
コード例 #4
0
ファイル: main.go プロジェクト: krionux/goploader
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)
}
コード例 #5
0
ファイル: util.go プロジェクト: cubeee/go-sig
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
}
コード例 #6
0
ファイル: encrypt.go プロジェクト: kobeld/goutils
// 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
}
コード例 #7
0
ファイル: crypt.go プロジェクト: andradeandrey/goadmin
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
}
コード例 #8
0
ファイル: aes.go プロジェクト: mohoff/CryptoWrapper
// 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
}
コード例 #9
0
ファイル: aes.go プロジェクト: dulumao/ant
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
}
コード例 #10
0
ファイル: main.go プロジェクト: fernandopn/flashSafe
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)
}
コード例 #11
0
ファイル: cipher.go プロジェクト: detailyang/hikarian
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
}
コード例 #12
0
ファイル: aes.go プロジェクト: kingfree/haut
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)
}
コード例 #13
0
ファイル: encryption.go プロジェクト: Hermes/hermes
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))
}
コード例 #14
0
ファイル: fclient.go プロジェクト: NichoZhang/fakio
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
}
コード例 #15
0
ファイル: conceal.go プロジェクト: dieucao/notifications
// 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
}
コード例 #16
0
ファイル: cipherfactory.go プロジェクト: cinode/archive-golib
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
}
コード例 #17
0
ファイル: udp.go プロジェクト: s752550916/v2ray-core
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
}
コード例 #18
0
ファイル: cipher.go プロジェクト: applepi-icpc/icarus
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
}
コード例 #19
0
ファイル: main.go プロジェクト: tcnksm/go-crypto
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))
}
コード例 #20
0
ファイル: 20111126_des.go プロジェクト: bonly/exercise
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)
}
コード例 #21
0
ファイル: aes.go プロジェクト: ylywyn/v2ray-core
// NewAesDecryptionStream creates a new AES encryption stream based on given key and IV.
// Caller must ensure the length of key and IV is either 16, 24 or 32 bytes.
func NewAesDecryptionStream(key []byte, iv []byte) cipher.Stream {
	aesBlock, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}
	return cipher.NewCFBDecrypter(aesBlock, iv)
}
コード例 #22
0
ファイル: crypto.go プロジェクト: nicnys-8/mdc
func decryptAes(hexKey string, ciphertext string) (string, error) {
	key, err := hex2Bin(hexKey)
	if err != nil {
		panic(err)
	}

	text, err := decodeBase64(ciphertext)
	if err != nil {
		return "", err
	}

	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		panic(err)
	}
	if len(text) < aes.BlockSize {
		panic("ciphertext too short")
	}
	iv := text[:aes.BlockSize]
	text = text[aes.BlockSize:]
	cfb := cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(text, text)

	temp, err := decodeBase64(string(text))
	if err != nil {
		return "", err
	}

	return string(temp), nil
}
コード例 #23
0
func DecryptAESCFB(src, key []byte) *AuthToken {
	encrData := EncrData{}
	err := json.Unmarshal(src, &encrData)
	if err != nil {
		return nil
	}

	if len(encrData.IV) != len(key) {
		return nil
	}

	rawBytes := make([]byte, len(encrData.Data))
	cipher.NewCFBDecrypter(aesCipher(key), encrData.IV).XORKeyStream(rawBytes, encrData.Data)

	rawData := RawData{}
	err = json.Unmarshal(rawBytes, &rawData)
	if err != nil {
		return nil
	}

	cSum := crc32.ChecksumIEEE(rawData.Data)
	if cSum != rawData.CSum {
		return nil
	}

	res := AuthToken{}
	err = json.Unmarshal(rawData.Data, &res)
	if err != nil {
		return nil
	}

	return &res
}
コード例 #24
0
ファイル: crypto.go プロジェクト: runner-mei/snmpclient
func sc_aes_crypt(isEncrypt bool, engine_boots, engine_time int, msg_salt, key, data []byte) error {

	if 0 == len(data) {
		return fmt.Errorf("len(input_data) != 0, actual len is 0")
	}

	if 8 != len(msg_salt) {
		return fmt.Errorf("len(msg_salt) != 8, actual len is %d", len(msg_salt))
	}
	initVec := make([]byte, 8+len(msg_salt))

	binary.BigEndian.PutUint32(initVec, uint32(engine_boots))
	binary.BigEndian.PutUint32(initVec[4:], uint32(engine_time))
	copy(initVec[8:], msg_salt)

	block, err := aes.NewCipher(key)
	if nil != err {
		return err
	}
	if isEncrypt {
		cipher.NewCFBEncrypter(block, initVec).
			XORKeyStream(data, data)
	} else {
		cipher.NewCFBDecrypter(block, initVec).
			XORKeyStream(data, data)
	}
	return nil
}
コード例 #25
0
ファイル: ut_aes.go プロジェクト: st2py/bitcrypt
func AesDecryptData(data, key []byte, ctp string) []byte {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil
	}

	if len(data) < aes.BlockSize {
		return nil
	}

	iv := data[:aes.BlockSize]
	data_dec := data[aes.BlockSize:]

	var stream cipher.Stream
	switch ctp {
	case "cfb":
		stream = cipher.NewCFBDecrypter(block, iv)
	case "ctr":
		stream = cipher.NewCTR(block, iv)
	default:
		stream = cipher.NewOFB(block, iv)
	}

	// XORKeyStream can work in-place if the two arguments are the same.
	stream.XORKeyStream(data_dec, data_dec)
	return data_dec
}
コード例 #26
0
ファイル: encryption.go プロジェクト: danieljoos/keyfwd
// Decrypts the given byte array.
// The function expects the given data to include the initialization vector
// within the first bytes (0 to BlockSize(16)). The remaining bytes contain the actual
// data to decrypt.
// Returns the decrypted data as byte array.
func (t *Encryption) Decrypt(data []byte) []byte {
	blockSize := t.cipher.BlockSize()
	decrypter := cipher.NewCFBDecrypter(t.cipher, data[0:blockSize])
	ret := make([]byte, len(data)-blockSize)
	decrypter.XORKeyStream(ret, data[blockSize:len(data)])
	return ret
}
コード例 #27
0
ファイル: CryptTest.go プロジェクト: jerusalemdax/GoTest
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)
}
コード例 #28
0
ファイル: mahmut.go プロジェクト: melihmucuk/mahmut
// Coz decrypts the cryptoText with the given key.
func Coz(key string, cryptoText 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
	}

	ciphertext, _ := base64.StdEncoding.DecodeString(cryptoText)

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

	if len(ciphertext) < aes.BlockSize {
		return "", errors.New("ciphertext too short")
	}
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

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

	return fmt.Sprintf("%s", ciphertext), nil
}
コード例 #29
0
ファイル: security.go プロジェクト: mgenov/snmpgo
func decryptAES(src, key, privParam []byte, engineBoots, engineTime int32) (
	dst []byte, err error) {

	if len(privParam) != 8 {
		err = ArgumentError{
			Value:   len(privParam),
			Message: "Invalid AES PrivParameter length",
		}
		return
	}

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

	var buf bytes.Buffer
	binary.Write(&buf, binary.BigEndian, engineBoots)
	binary.Write(&buf, binary.BigEndian, engineTime)
	iv := append(buf.Bytes(), privParam...)

	dst = make([]byte, len(src))

	mode := cipher.NewCFBDecrypter(block, iv)
	mode.XORKeyStream(dst, src)
	return
}
コード例 #30
0
ファイル: validation.go プロジェクト: bradclawsie/code
// DecryptToken takes the base64-encoding of an encrypted session token
// and attempts to decrypt it into the clear-text token originally encrypted,
// which is typically generated by MakeUserFormTokenText.
func DecryptToken(session_token_b64 string,key []byte) (string,error) {
	// prepare the key
	block, block_err := aes.NewCipher(key)
	if block_err != nil {
		return "",block_err
	}
	// take the base64-encoded encrypted token and decode it to bytes
	session_token_b64_bytes,decode_token_b64_bytes_err := base64.StdEncoding.DecodeString(session_token_b64)
	if decode_token_b64_bytes_err != nil {
		return "",decode_token_b64_bytes_err
	}
	// validate and decrypt with our key
	if len(session_token_b64_bytes) < aes.BlockSize {
		return "",errors.New("session token bytes too short")
	}
	// get iv
	iv := session_token_b64_bytes[:aes.BlockSize]
	session_token_b64_bytes = session_token_b64_bytes[aes.BlockSize:]
	cfb := cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(session_token_b64_bytes,session_token_b64_bytes)
	// now we have a decrypted string which was also base64 encoded. decode that to bytes.
	decrypted_session_token_bytes,decode_token_str_err := 
		base64.StdEncoding.DecodeString(string(session_token_b64_bytes))
	if decode_token_str_err != nil {
		return "",decode_token_str_err
	}
	// return the string representation of the decrypted bytes
	return string(decrypted_session_token_bytes),nil
}