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