Esempio n. 1
0
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
}
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))
}
Esempio n. 3
0
File: server.go Progetto: Syfaro/mc
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
}
Esempio n. 4
0
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
}
Esempio n. 5
0
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
}
Esempio n. 6
0
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)
	}
}
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)
	}
}
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)
	}
}
Esempio n. 9
0
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
}
Esempio n. 10
0
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
}
Esempio n. 11
0
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
}
Esempio n. 12
0
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
}
Esempio n. 13
0
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
}
Esempio n. 14
0
func cipherAES(key, iv []byte, isRead bool) interface{} {
	block, _ := aes.NewCipher(key)
	if isRead {
		return cipher.NewCBCDecrypter(block, iv)
	}
	return cipher.NewCBCEncrypter(block, iv)
}
Esempio n. 15
0
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
	}
}
Esempio n. 16
0
func (c *Conversation) generateDHCommit() []byte {
	_, err := io.ReadFull(c.rand(), c.r[:])
	if err != nil {
		panic("otr: short read from random source")
	}

	var xBytes [dhPrivateBytes]byte
	c.x = c.randMPI(xBytes[:])
	c.gx = new(big.Int).Exp(g, c.x, p)
	c.gy = nil
	c.gxBytes = appendMPI(nil, c.gx)

	h := sha256.New()
	h.Write(c.gxBytes)
	h.Sum(c.digest[:0])

	aesCipher, err := aes.NewCipher(c.r[:])
	if err != nil {
		panic(err.Error())
	}

	var iv [aes.BlockSize]byte
	ctr := cipher.NewCTR(aesCipher, iv[:])
	ctr.XORKeyStream(c.gxBytes, c.gxBytes)

	return c.serializeDHCommit()
}
Esempio n. 17
0
func TestOFB(t *testing.T) {
	for _, tt := range ofbTests {
		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
		}

		for j := 0; j <= 5; j += 5 {
			plaintext := tt.in[0 : len(tt.in)-j]
			ofb := cipher.NewOFB(c, tt.iv)
			ciphertext := make([]byte, len(plaintext))
			ofb.XORKeyStream(ciphertext, plaintext)
			if !bytes.Equal(ciphertext, tt.out[:len(plaintext)]) {
				t.Errorf("%s/%d: encrypting\ninput % x\nhave % x\nwant % x", test, len(plaintext), plaintext, ciphertext, tt.out)
			}
		}

		for j := 0; j <= 5; j += 5 {
			ciphertext := tt.out[0 : len(tt.in)-j]
			ofb := cipher.NewOFB(c, tt.iv)
			plaintext := make([]byte, len(ciphertext))
			ofb.XORKeyStream(plaintext, ciphertext)
			if !bytes.Equal(plaintext, tt.in[:len(ciphertext)]) {
				t.Errorf("%s/%d: decrypting\nhave % x\nwant % x", test, len(ciphertext), plaintext, tt.in)
			}
		}

		if t.Failed() {
			break
		}
	}
}
Esempio n. 18
0
func main() {
	plainText := []byte("Bob loves Alice. But Alice hate Bob...")
	key := []byte("passw0rdpassw0rdpassw0rdpassw0rd")

	// Create new AES 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.NewCTR(block, iv)
	encryptStream.XORKeyStream(cipherText[aes.BlockSize:], plainText)
	fmt.Printf("Cipher text: %x \n", cipherText)

	// Decrpt
	decryptedText := make([]byte, len(cipherText[aes.BlockSize:]))
	decryptStream := cipher.NewCTR(block, cipherText[:aes.BlockSize])
	decryptStream.XORKeyStream(decryptedText, cipherText[aes.BlockSize:])
	fmt.Printf("Decrypted text: %s\n", string(decryptedText))
}
func TestCBC(t *testing.T) {
	msg := []byte("12345678901234567890")
	key := RandAes128()
	iv := RandBytes(16)
	block, _ := aes.NewCipher(key)
	padded := PadTo(msg, 16)
	ct := make([]byte, len(padded))
	CBCEncrypt(block, iv, ct, padded)

	block, _ = aes.NewCipher(key)
	padded2 := make([]byte, len(ct))
	CBCDecrypt(block, iv, padded2, ct)
	if bytes.Compare(padded, padded2) != 0 {
		t.Errorf("expected %x, got %x", padded, padded2)
	}
}
Esempio n. 20
0
func (v *Vault) DecryptEnvironments(password string) (map[string]Environment, error) {
	if v.MACDigest != "sha-256" && v.Cipher != "aes" && v.CipherMode != "ctr" {
		return nil, ErrInvalidEncryptionConfig
	}

	// derive the key
	key, err := v.KeyDetails.key(password)
	if err != nil {
		return nil, err
	}

	// validate the mac
	if !hmac.Equal(v.mac(key), v.MAC) {
		return nil, ErrInvalidPassword
	}

	// decrypt the environments
	plaintext := make([]byte, len(v.Environments))

	block, err := aes.NewCipher(key)
	decrypter := cipher.NewCTR(block, v.IV)
	decrypter.XORKeyStream(plaintext, v.Environments)

	// unmarshal the environments
	environments := map[string]Environment{}
	err = json.Unmarshal(plaintext, &environments)
	if err != nil {
		return nil, err
	}

	return environments, nil
}
Esempio n. 21
0
func newAESCTR(key, iv []byte) (cipher.Stream, error) {
	c, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	return cipher.NewCTR(c, iv), nil
}
Esempio n. 22
0
func DecryptIO(reader io.Reader, writer io.Writer, passphrase string) (mac []byte, e error) {
	key := PassphraseToKey(passphrase)
	hashMac := hmac.New(sha256.New, key)
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	iv := make([]byte, aes.BlockSize)
	if _, err = io.ReadFull(reader, iv); err != nil {
		return nil, err
	}
	stream := cipher.NewOFB(block, iv)
	cipherReader := &cipher.StreamReader{S: stream, R: reader}
	pp := make([]byte, len([]byte(passphrase)))
	if _, err = io.ReadFull(cipherReader, pp); err != nil {
		return nil, err
	}
	if passphrase != string(pp) {
		return nil, errors.New("Incorrect passphrase")
	}
	mw := io.MultiWriter(writer, hashMac)
	if _, err = io.Copy(mw, cipherReader); err != nil {
		return nil, err
	}
	return hashMac.Sum(nil), nil
}
Esempio n. 23
0
func EncryptIO(reader io.Reader, writer io.Writer, passphrase string) (mac []byte, e error) {
	key := PassphraseToKey(passphrase)
	hashMac := hmac.New(sha256.New, key)
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	iv := make([]byte, aes.BlockSize)
	if _, err = io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}
	stream := cipher.NewOFB(block, iv)
	_, err = writer.Write(iv)
	if err != nil {
		return nil, err
	}
	cipherWriter := &cipher.StreamWriter{S: stream, W: writer}
	_, err = cipherWriter.Write([]byte(passphrase))
	if err != nil {
		return nil, err
	}
	mw := io.MultiWriter(cipherWriter, hashMac)
	if _, err = io.Copy(mw, reader); err != nil {
		return nil, err
	}
	return hashMac.Sum(nil), nil
}
Esempio n. 24
0
func (alg *AesGcm) Encrypt(aad, plainText, cek []byte) (iv, cipherText, authTag []byte, err error) {

	cekSizeBits := len(cek) << 3

	if cekSizeBits != alg.keySizeBits {
		return nil, nil, nil, errors.New(fmt.Sprintf("AesGcm.Encrypt(): expected key of size %v bits, but was given %v bits.", alg.keySizeBits, cekSizeBits))
	}

	if iv, err = arrays.Random(12); err != nil {
		return nil, nil, nil, err
	}

	var block cipher.Block

	if block, err = aes.NewCipher(cek); err != nil {
		return nil, nil, nil, err
	}

	var aesgcm cipher.AEAD

	if aesgcm, err = cipher.NewGCM(block); err != nil {
		return nil, nil, nil, err
	}

	cipherWithTag := aesgcm.Seal(nil, iv, plainText, aad)

	cipherText = cipherWithTag[:len(cipherWithTag)-aesgcm.Overhead()]
	authTag = cipherWithTag[len(cipherWithTag)-aesgcm.Overhead():]

	return iv, cipherText, authTag, nil
}
Esempio n. 25
0
func (alg *AesGcm) Decrypt(aad, cek, iv, cipherText, authTag []byte) (plainText []byte, err error) {

	cekSizeBits := len(cek) << 3

	if cekSizeBits != alg.keySizeBits {
		return nil, errors.New(fmt.Sprintf("AesGcm.Decrypt(): expected key of size %v bits, but was given %v bits.", alg.keySizeBits, cekSizeBits))
	}

	var block cipher.Block

	if block, err = aes.NewCipher(cek); err != nil {
		return nil, err
	}

	var aesgcm cipher.AEAD

	if aesgcm, err = cipher.NewGCM(block); err != nil {
		return nil, err
	}

	cipherWithTag := append(cipherText, authTag...)

	if plainText, err = aesgcm.Open(nil, iv, cipherWithTag, aad); err != nil {
		return nil, err
	}

	return plainText, nil
}
Esempio n. 26
0
func TestAesKeyWrapInvalid(t *testing.T) {
	kek, _ := hex.DecodeString("000102030405060708090A0B0C0D0E0F")

	// Invalid unwrap input (bit flipped)
	input0, _ := hex.DecodeString("1EA68C1A8112B447AEF34BD8FB5A7B828D3E862371D2CFE5")

	block, _ := aes.NewCipher(kek)

	_, err := KeyUnwrap(block, input0)
	if err == nil {
		t.Error("key unwrap failed to detect invalid input")
	}

	// Invalid unwrap input (truncated)
	input1, _ := hex.DecodeString("1EA68C1A8112B447AEF34BD8FB5A7B828D3E862371D2CF")

	_, err = KeyUnwrap(block, input1)
	if err == nil {
		t.Error("key unwrap failed to detect truncated input")
	}

	// Invalid wrap input (not multiple of 8)
	input2, _ := hex.DecodeString("0123456789ABCD")

	_, err = KeyWrap(block, input2)
	if err == nil {
		t.Error("key wrap accepted invalid input")
	}

}
Esempio n. 27
0
// Method Close encrypts and writes the encrypted data to the key file
func (k *KeyStore) Close(secret []byte) {
	// Encode a gob of the keystore
	var buff bytes.Buffer
	enc := gob.NewEncoder(&buff)
	enc.Encode(k)
	buffString := buff.String()

	// Encrypt the data
	block, err := aes.NewCipher(secret)
	if err != nil {
		panic(err)
	}
	ciphertext := make([]byte, aes.BlockSize+len(buffString))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}
	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(buffString))

	// Write the encrypted data to the file
	kFile, err := os.OpenFile(kf, os.O_WRONLY, 0644)
	if err != nil {
		panic(err)
	}
	bytesWritten, err := kFile.Write(ciphertext)
	if err != nil || bytesWritten == 0 {
		panic(err)
	}
}
Esempio n. 28
0
// Decrypt decrypts a value using the given key with AES.
//
// The value to be decrypted must be prepended by a initialization vector
// (http://goo.gl/zF67k) with the length of the block size.
func Decrypt(blockKey []byte, value []byte) ([]byte, error) {

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

	size := block.BlockSize()
	if len(value) > size {
		// Extract iv.
		iv := value[:size]

		// Extract ciphertext.
		value = value[size:]

		// Decrypt it.
		stream := cipher.NewCTR(block, iv)
		stream.XORKeyStream(value, value)

		// Return on success
		return value, nil
	}

	return nil, errors.New("the value could not be decrypted")
}
Esempio n. 29
0
func TestCookieEncodeDecode(t *testing.T) {
	hashKey := "testhashKey"
	blockkey := generateRandomKey(16)
	block, err := aes.NewCipher(blockkey)
	if err != nil {
		t.Fatal("NewCipher:", err)
	}
	securityName := string(generateRandomKey(20))
	val := make(map[interface{}]interface{})
	val["name"] = "mikeqian"
	val["gender"] = "male"
	str, err := encodeCookie(block, hashKey, securityName, val)
	if err != nil {
		t.Fatal("encodeCookie:", err)
	}
	dst := make(map[interface{}]interface{})
	dst, err = decodeCookie(block, hashKey, securityName, str, 3600)
	if err != nil {
		t.Fatal("decodeCookie", err)
	}
	if dst["name"] != "mikeqian" {
		t.Fatal("dst get map error")
	}
	if dst["gender"] != "male" {
		t.Fatal("dst get map error")
	}
}
Esempio n. 30
0
func (c *Conn) decryptTicket(encrypted []byte) (*sessionState, bool) {
	if len(encrypted) < aes.BlockSize+sha256.Size {
		return nil, false
	}

	iv := encrypted[:aes.BlockSize]
	macBytes := encrypted[len(encrypted)-sha256.Size:]

	mac := hmac.New(sha256.New, c.config.SessionTicketKey[16:32])
	mac.Write(encrypted[:len(encrypted)-sha256.Size])
	expected := mac.Sum(nil)

	if subtle.ConstantTimeCompare(macBytes, expected) != 1 {
		return nil, false
	}

	block, err := aes.NewCipher(c.config.SessionTicketKey[:16])
	if err != nil {
		return nil, false
	}
	ciphertext := encrypted[aes.BlockSize : len(encrypted)-sha256.Size]
	plaintext := make([]byte, len(ciphertext))
	cipher.NewCTR(block, iv).XORKeyStream(plaintext, ciphertext)

	state := new(sessionState)
	ok := state.unmarshal(plaintext)
	return state, ok
}