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


Golang aes.NewCipher函數代碼示例

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


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

示例1: CreateExchangedCipher

func CreateExchangedCipher(peerPub, priv []byte) (Cipher, Cipher, error) {
	x, y := elliptic.Unmarshal(curve, peerPub)

	sx, _ := curve.ScalarMult(x, y, priv)

	secret := cryptohash(sx.Bytes())

	aesKey1 := secret[0:aes.BlockSize]
	aesKey2 := secret[aes.BlockSize : 2*aes.BlockSize]
	vector1 := secret[2*aes.BlockSize : 3*aes.BlockSize]
	vector2 := secret[3*aes.BlockSize : 4*aes.BlockSize]

	block1, err := aes.NewCipher(aesKey1)

	if err != nil {
		return nil, nil, err
	}

	block2, err := aes.NewCipher(aesKey2)

	if err != nil {
		return nil, nil, err
	}

	stream1 := cipher.NewOFB(block1, vector1)
	stream2 := cipher.NewOFB(block2, vector2)

	return stream1, stream2, nil
}
開發者ID:rovaughn,項目名稱:nimbus,代碼行數:29,代碼來源:encryption.go

示例2: main

func main() {
	encoded := util.ReadFile("25.txt")
	bytes, err := base64.StdEncoding.DecodeString(string(encoded))
	if err != nil {
		log.Fatal(err)
	}
	oldAes, err := aes.NewCipher([]byte("YELLOW SUBMARINE"))
	if err != nil {
		log.Fatal(err)
	}
	util.ECBDecrypt(oldAes, bytes, bytes)
	// we have plaintext in bytes

	// encrypt it in CTR mode
	block, err := aes.NewCipher(key)
	if err != nil {
		log.Fatal(err)
	}
	util.CTREncrypt(block, nonce, bytes, bytes)

	// save the copy
	ct := make([]byte, len(bytes))
	copy(ct, bytes)

	// let's prepare sequence of 0 bytes and replace the text with it
	zeroes := make([]byte, len(bytes))
	edit(bytes, 0, zeroes)
	// result in bytes contains the key
	// let's recover the original plain text:
	for i := 0; i < len(ct); i++ {
		bytes[i] = ct[i] ^ bytes[i]
	}
	fmt.Println(string(bytes))
}
開發者ID:ysmolsky,項目名稱:cryptopals-matasano-solutions,代碼行數:34,代碼來源:main.go

示例3: newEncryptedStream

func newEncryptedStream(conn io.ReadWriter, key []byte) (s *encryptedStream, err error) {
	rcipher, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

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

	rstream := cipher.NewCFBDecrypter(rcipher, key)
	wstream := cipher.NewCFBEncrypter(wcipher, key)

	return &encryptedStream{
		StreamReader: cipher.StreamReader{
			S: rstream,
			R: conn,
		},

		StreamWriter: cipher.StreamWriter{
			S: wstream,
			W: conn,
		},
	}, nil
}
開發者ID:Syfaro,項目名稱:mc,代碼行數:26,代碼來源:server.go

示例4: kdf

func (conn *obfs3Conn) kdf(sharedSecret []byte) error {
	// Using that shared-secret each party derives its encryption keys as
	// follows:
	//
	//   INIT_SECRET = HMAC(SHARED_SECRET, "Initiator obfuscated data")
	//   RESP_SECRET = HMAC(SHARED_SECRET, "Responder obfuscated data")
	//   INIT_KEY = INIT_SECRET[:KEYLEN]
	//   INIT_COUNTER = INIT_SECRET[KEYLEN:]
	//   RESP_KEY = RESP_SECRET[:KEYLEN]
	//   RESP_COUNTER = RESP_SECRET[KEYLEN:]
	initHmac := hmac.New(sha256.New, sharedSecret)
	initHmac.Write([]byte(initiatorKdfString))
	initSecret := initHmac.Sum(nil)
	initHmac.Reset()
	initHmac.Write([]byte(initiatorMagicString))
	initMagic := initHmac.Sum(nil)

	respHmac := hmac.New(sha256.New, sharedSecret)
	respHmac.Write([]byte(responderKdfString))
	respSecret := respHmac.Sum(nil)
	respHmac.Reset()
	respHmac.Write([]byte(responderMagicString))
	respMagic := respHmac.Sum(nil)

	// The INIT_KEY value keys a block cipher (in CTR mode) used to
	// encrypt values from initiator to responder thereafter.  The counter
	// mode's initial counter value is INIT_COUNTER.  The RESP_KEY value
	// keys a block cipher (in CTR mode) used to encrypt values from
	// responder to initiator thereafter.  That counter mode's initial
	// counter value is RESP_COUNTER.
	//
	// Note: To have this be the last place where the shared secret is used,
	// also generate the magic value to send/scan for here.
	initBlock, err := aes.NewCipher(initSecret[:keyLen])
	if err != nil {
		return err
	}
	initStream := cipher.NewCTR(initBlock, initSecret[keyLen:])

	respBlock, err := aes.NewCipher(respSecret[:keyLen])
	if err != nil {
		return err
	}
	respStream := cipher.NewCTR(respBlock, respSecret[keyLen:])

	if conn.isInitiator {
		conn.tx = &cipher.StreamWriter{S: initStream, W: conn.Conn}
		conn.rx = &cipher.StreamReader{S: respStream, R: conn.rxBuf}
		conn.txMagic = initMagic
		conn.rxMagic = respMagic
	} else {
		conn.tx = &cipher.StreamWriter{S: respStream, W: conn.Conn}
		conn.rx = &cipher.StreamReader{S: initStream, R: conn.rxBuf}
		conn.txMagic = respMagic
		conn.rxMagic = initMagic
	}

	return nil
}
開發者ID:OperatorFoundation,項目名稱:obfs4,代碼行數:59,代碼來源:obfs3.go

示例5: create_ciphers

func create_ciphers() *[]block.Cipher {
	ciphers := make([]block.Cipher, 6)
	ciphers[0], _ = des.NewDESCipher(key)
	ciphers[1], _ = des.NewDES2Cipher(key2)
	ciphers[2], _ = des.NewDES3Cipher(key3)
	ciphers[3], _ = aes.NewCipher(aes128key)
	ciphers[4], _ = aes.NewCipher(aes192key)
	ciphers[5], _ = aes.NewCipher(aes256key)
	return &ciphers
}
開發者ID:a2800276,項目名稱:des.go,代碼行數:10,代碼來源:bench.go

示例6: TestAesKeyWrap

func TestAesKeyWrap(t *testing.T) {
	// Test vectors from: http://csrc.nist.gov/groups/ST/toolkit/documents/kms/key-wrap.pdf
	kek0, _ := hex.DecodeString("000102030405060708090A0B0C0D0E0F")
	cek0, _ := hex.DecodeString("00112233445566778899AABBCCDDEEFF")

	expected0, _ := hex.DecodeString("1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5")

	kek1, _ := hex.DecodeString("000102030405060708090A0B0C0D0E0F1011121314151617")
	cek1, _ := hex.DecodeString("00112233445566778899AABBCCDDEEFF")

	expected1, _ := hex.DecodeString("96778B25AE6CA435F92B5B97C050AED2468AB8A17AD84E5D")

	kek2, _ := hex.DecodeString("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F")
	cek2, _ := hex.DecodeString("00112233445566778899AABBCCDDEEFF0001020304050607")

	expected2, _ := hex.DecodeString("A8F9BC1612C68B3FF6E6F4FBE30E71E4769C8B80A32CB8958CD5D17D6B254DA1")

	block0, _ := aes.NewCipher(kek0)
	block1, _ := aes.NewCipher(kek1)
	block2, _ := aes.NewCipher(kek2)

	out0, _ := KeyWrap(block0, cek0)
	out1, _ := KeyWrap(block1, cek1)
	out2, _ := KeyWrap(block2, cek2)

	if bytes.Compare(out0, expected0) != 0 {
		t.Error("output 0 not as expected, got", out0, "wanted", expected0)
	}

	if bytes.Compare(out1, expected1) != 0 {
		t.Error("output 1 not as expected, got", out1, "wanted", expected1)
	}

	if bytes.Compare(out2, expected2) != 0 {
		t.Error("output 2 not as expected, got", out2, "wanted", expected2)
	}

	unwrap0, _ := KeyUnwrap(block0, out0)
	unwrap1, _ := KeyUnwrap(block1, out1)
	unwrap2, _ := KeyUnwrap(block2, out2)

	if bytes.Compare(unwrap0, cek0) != 0 {
		t.Error("key unwrap did not return original input, got", unwrap0, "wanted", cek0)
	}

	if bytes.Compare(unwrap1, cek1) != 0 {
		t.Error("key unwrap did not return original input, got", unwrap1, "wanted", cek1)
	}

	if bytes.Compare(unwrap2, cek2) != 0 {
		t.Error("key unwrap did not return original input, got", unwrap2, "wanted", cek2)
	}
}
開發者ID:CometKim,項目名稱:platform,代碼行數:53,代碼來源:key_wrap_test.go

示例7: newBlockCipher

func newBlockCipher(name string, key []byte) (cipher.Block, error) {
	switch name {
	case "aes128":
		return aes.NewCipher(key)
	case "aes256":
		return aes.NewCipher(key)
	case "3des":
		return des.NewTripleDESCipher(key)
	default:
		return nil, fmt.Errorf("unknown cipher '%s'", name)
	}
}
開發者ID:GaloisInc,項目名稱:hacrypto,代碼行數:12,代碼來源:make_legacy_aead_tests.go

示例8: TestEncoder

func TestEncoder(t *testing.T) {
	b, err := aes.NewCipher([]byte("1234567890123456"))
	if err != nil {
		t.Error(err)
	}
	e1 := Encoder{
		Hash:  hmac.NewSHA256([]byte("secret-key1")),
		Block: b,
	}

	b, err = aes.NewCipher([]byte("0123456789012345"))
	if err != nil {
		t.Error(err)
	}
	e2 := Encoder{
		Hash:  hmac.NewSHA256([]byte("secret-key2")),
		Block: b,
	}

	value := make(SessionData)
	value["foo"] = "bar"
	value["baz"] = 128

	var count int
	for i := 0; i < 50; i++ {
		// Running this multiple times to check if any special character
		// breaks encoding/decoding.
		value := make(SessionData)
		value["foo"] = "bar"
		value["baz"] = 128

		encoded, err2 := e1.Encode("sid", value)
		if err2 != nil {
			t.Error(err2)
		}
		decoded, err3 := e1.Decode("sid", encoded)
		if err3 != nil {
			t.Errorf("%v: %v", err3, encoded)
			count++
		}
		if fmt.Sprintf("%v", decoded) != fmt.Sprintf("%v", value) {
			t.Errorf("Expected %v, got %v.", value, decoded)
		}
		_, err4 := e2.Decode("sid", encoded)
		if err4 == nil {
			t.Errorf("Expected failure decoding.")
		}
	}
	if count > 0 {
		t.Errorf("%d errors out of 100.", count)
	}
}
開發者ID:scyth,項目名稱:gorilla-sessions-filestore,代碼行數:52,代碼來源:sessions_test.go

示例9: NewTunnelCrypto

func NewTunnelCrypto(layerKey, ivKey TunnelKey) (t *Tunnel, err error) {

	t = new(Tunnel)
	t.layerKey, err = aes.NewCipher(layerKey[:])
	if err == nil {
		t.ivKey, err = aes.NewCipher(ivKey[:])
	}

	if err != nil {
		// error happened we don't need t
		t = nil
	}
	return
}
開發者ID:majestrate,項目名稱:go-i2p,代碼行數:14,代碼來源:tunnel.go

示例10: SetKey

func (e *aesEngine) SetKey(encrypt, decrypt []byte) (err error) {
	var ecb, dcb cipher.Block
	if len(encrypt) != AESBlockSize {
		return errors.New("encrypt.bad key size")
	} else if ecb, err = aes.NewCipher(encrypt); err != nil {
		return errors.New("encrypt.create error")
	}
	if len(decrypt) != AESBlockSize {
		return errors.New("decrypt.bad key size")
	} else if dcb, err = aes.NewCipher(decrypt); err != nil {
		return errors.New("decrypt.create error")
	}
	e.ecb, e.dcb = ecb, dcb
	return
}
開發者ID:Yuhang,項目名稱:xserver,代碼行數:15,代碼來源:aes.go

示例11: generateStream

func generateStream(seed, label []byte) io.Reader {
	// Generate sub-key
	subKey := make([]byte, 16)
	c, _ := aes.NewCipher(seed)
	c.Encrypt(subKey, label)

	// Create pseudo-random byte stream keyed by sub-key.
	block, _ := aes.NewCipher(subKey)
	stream := cipher.StreamReader{
		cipher.NewCTR(block, label),
		devNull{},
	}

	return stream
}
開發者ID:gaurav1981,項目名稱:AES,代碼行數:15,代碼來源:keygen_tools.go

示例12: encrypt

func encrypt(key []byte, text string) (string, error) {

	if text == "" || text == "{}" {
		return "", nil
	}

	plaintext := []byte(text)
	skey := sha512.Sum512(key)
	ekey, akey := skey[:32], skey[32:]

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

	macfn := hmac.New(sha256.New, akey)
	ciphertext := make([]byte, aes.BlockSize+macfn.Size()+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(crand.Reader, iv); err != nil {
		return "", err
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize+macfn.Size():], plaintext)
	macfn.Write(ciphertext[aes.BlockSize+macfn.Size():])
	mac := macfn.Sum(nil)
	copy(ciphertext[aes.BlockSize:aes.BlockSize+macfn.Size()], mac)

	return base64.URLEncoding.EncodeToString(ciphertext), nil
}
開發者ID:alphafeng,項目名稱:platform,代碼行數:30,代碼來源:sql_store.go

示例13: decryptAES

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
}
開發者ID:mgenov,項目名稱:snmpgo,代碼行數:27,代碼來源:security.go

示例14: 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

示例15: streamCipherReaderForKeyData

func streamCipherReaderForKeyData(keyType byte, keyData []byte, r io.ReadCloser) (io.ReadCloser, error) {

	switch keyType {
	case keyTypeAES:
		if len(keyData) != keyTypeAESKeySize {
			return nil, ErrInvalidKey
		}
		// Ignore error below, aes will fail only if the size of key is
		// invalid. We fully control it and pass valid value.
		block, _ := aes.NewCipher(keyData)
		var iv [aes.BlockSize]byte
		stream := cipher.NewCTR(block, iv[:])
		return &streamReader{cipher.StreamReader{S: stream, R: r}}, nil

	case keyTypeChaCha20:
		if len(keyData) != chacha20.KeySize {
			return nil, ErrInvalidKey
		}
		var nonce [chacha20.NonceSize]byte
		// Ignore error below, chacha20 will fail only if the size of key or
		// nonce are invalid. We fully control those and pass valid values.
		stream, _ := chacha20.NewCipher(keyData, nonce[:])
		return &streamReader{cipher.StreamReader{S: stream, R: r}}, nil

	default:
		return nil, ErrInvalidKey
	}
}
開發者ID:cinode,項目名稱:go,代碼行數:28,代碼來源:cipher_factory.go


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