Esempio n. 1
2
func NewBlock(method string, keyfile string) (c cipher.Block, err error) {
	logger.Debugf("Crypt Wrapper with %s preparing.", method)

	file, err := os.Open(keyfile)
	if err != nil {
		return
	}
	defer file.Close()

	key := make([]byte, KEYSIZE)
	_, err = io.ReadFull(file, key)
	if err != nil {
		return
	}

	switch method {
	case "aes":
		c, err = aes.NewCipher(key)
	case "des":
		c, err = des.NewCipher(key)
	case "tripledes":
		c, err = des.NewTripleDESCipher(key)
	}
	return
}
Esempio n. 2
1
func (p *PasswordAuth) encrypt(key string, bytes []byte) ([]byte, error) {
	keyBytes := []byte{0, 0, 0, 0, 0, 0, 0, 0}

	if len(key) > 8 {
		key = key[:8]
	}

	for i := 0; i < len(key); i++ {
		keyBytes[i] = p.reverseBits(key[i])
	}

	block, err := des.NewCipher(keyBytes)

	if err != nil {
		return nil, err
	}

	result1 := make([]byte, 8)
	block.Encrypt(result1, bytes)
	result2 := make([]byte, 8)
	block.Encrypt(result2, bytes[8:])

	crypted := append(result1, result2...)

	return crypted, nil
}
Esempio n. 3
1
func cipherDES(key, iv []byte, isRead bool) interface{} {
	block, _ := des.NewCipher(key)
	if isRead {
		return cipher.NewCBCDecrypter(block, iv)
	}
	return cipher.NewCBCEncrypter(block, iv)
}
Esempio n. 4
0
func (s *descbc) Sign(algo, usage int, data ...[]byte) ([]byte, error) {
	var h hash.Hash

	switch algo {
	case signGssDes:
		sz := 0
		for _, d := range data {
			sz += len(d)
		}
		sz = (sz + 7) &^ 7
		u := make([]byte, sz)
		v := u[:0]
		for _, d := range data {
			v = append(v, d...)
		}

		iv := [8]byte{}
		b, _ := des.NewCipher(s.key)
		c := cipher.NewCBCEncrypter(b, iv[:])
		c.CryptBlocks(u, u)
		return u[len(u)-8:], nil

	case signGssMd5Des:
		h = md5.New()
		for _, d := range data {
			h.Write(d)
		}
		return s.Sign(signGssDes, usage, h.Sum(nil))

	case signMd5Des:
		h = md5.New()
	case signMd4Des:
		h = md4.New()
	default:
		return unkeyedSign(algo, usage, data...)
	}

	var key [8]byte
	for i := 0; i < 8; i++ {
		key[i] = s.key[i] ^ 0xF0
	}

	chk := make([]byte, 24)
	io.ReadFull(rand.Reader, chk[:8])

	h.Write(chk[:8])
	for _, d := range data {
		h.Write(d)
	}
	h.Sum(chk[8:])

	iv := [8]byte{}
	b, _ := des.NewCipher(s.key)
	c := cipher.NewCBCEncrypter(b, iv[:])
	c.CryptBlocks(chk, chk)
	return chk, nil
}
Esempio n. 5
0
/*
介绍:创建默认DESCipher,使用ECB工作模式、pkcs57填充,算法秘钥长度64位 , 使用秘钥作为初始向量

作者:Alex
版本:release-1.1
*/
func NewDES(key []byte) (Cipher, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	return NewECBMode().Cipher(block, key[:block.BlockSize()]), nil
}
Esempio n. 6
0
func main() {
	plainText := []byte("Bob loves Alice.")

	// Key must be 8 bytes
	key := []byte("passw0rd")

	// Create Cipher block for DES
	block, err := des.NewCipher(key)
	if err != nil {
		fmt.Printf("err: %s", err)
	}

	// Create initialization vector from rand.reader
	iv := make([]byte, des.BlockSize)
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		fmt.Printf("err: %s", err)
		return
	}

	// Encrypt with CBC mode
	cipherText := make([]byte, len(plainText))
	encryptMode := cipher.NewCBCEncrypter(block, iv)
	encryptMode.CryptBlocks(cipherText, plainText)
	fmt.Printf("Cipher text: %v\n", cipherText)

	// Decrypt with CBC mode
	decryptedText := make([]byte, len(cipherText))
	decryptMode := cipher.NewCBCDecrypter(block, iv)
	decryptMode.CryptBlocks(decryptedText, cipherText)
	fmt.Printf("Decrypted text: %s\n", string(decryptedText))
}
Esempio n. 7
0
func check(key []byte, original uint64) {
	cipher, err := des.NewCipher(key)
	if err != nil {
		panic(err)
	}

	i2b := func(i uint64) (b []byte) {
		b = make([]byte, 8)
		binary.BigEndian.PutUint64(b, i)

		return b
	}

	originalPlainText := i2b(original)
	originalCipherText := make([]byte, 8)
	cipher.Encrypt(originalCipherText, originalPlainText)

	var (
		updated          uint64
		updatedPlainText []byte
	)
	updatedCipherText := make([]byte, 8)

	sum := 0.0
	for i := 0; i < 64; i++ {
		updated = original ^ (1 << uint64(i))
		updatedPlainText = i2b(updated)
		cipher.Encrypt(updatedCipherText, updatedPlainText)
		diffed := diff(originalCipherText, updatedCipherText)
		fmt.Printf("%d -> %d\n", i+1, diffed)
		sum += float64(diffed)
	}
	fmt.Printf("original: %d\n", original)
	fmt.Printf("mean: %f\n", sum/64)
}
Esempio n. 8
0
func (t *SubkeyTest) WrongBlockSize() {
	ciph, err := des.NewCipher(make([]byte, 8))
	AssertEq(nil, err)

	f := func() { generateSubkeys(ciph) }
	ExpectThat(f, Panics(HasSubstr("16 bytes")))
}
Esempio n. 9
0
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
}
Esempio n. 10
0
//[golang ECB 3DES Encrypt]
func TripleEcbDesEncrypt(origData, key []byte) ([]byte, error) {
	tkey := make([]byte, 24, 24)
	copy(tkey, key)
	k1 := tkey[:8]
	k2 := tkey[8:16]
	k3 := tkey[16:]

	block, err := des.NewCipher(k1)
	if err != nil {
		return nil, err
	}
	bs := block.BlockSize()
	origData = PKCS5Padding(origData, bs)

	buf1, err := encrypt(origData, k1)
	if err != nil {
		return nil, err
	}
	buf2, err := decrypt(buf1, k2)
	if err != nil {
		return nil, err
	}
	out, err := encrypt(buf2, k3)
	if err != nil {
		return nil, err
	}
	return out, nil
}
Esempio n. 11
0
/*
介绍:根据指定的工作模式,创建DESCipher,算法秘钥长度64位,使用秘钥作为初始向量

作者:Alex
版本:release-1.1
*/
func NewDESWith(key []byte, mode CipherMode) (Cipher, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	return mode.Cipher(block, key[:block.BlockSize()]), nil
}
Esempio n. 12
0
// Decrypt decrypts ciphertext in CBC mode and returns plaintext.
// ciphertext's length must be a multiple of 8. key is a 24 byte des key.
// iv is an 8 byte initialization vector. If iv is nil, zeros
// will be used as the initialization vector.
func Decrypt(ciphertext, key, iv []byte) ([]byte, error) {
	switch {
	case len(ciphertext)%8 != 0:
		return nil, errors.New("invalid ciphertext length")
	case len(key) != 24:
		return nil, errors.New("invalid key length")
	case iv == nil:
		iv = defaultIV
	case len(iv) != 8:
		return nil, errors.New("invalid iv length")
	}

	out := make([]byte, 0, len(ciphertext))
	prevXor := make([]byte, 8)
	temp := make([]byte, 8)

	preWhiten := key[8:16]
	postWhiten := key[16:24]
	cipher, err := des.NewCipher(key[:8])
	if err != nil {
		panic(err)
	}
	copy(prevXor, iv)

	for i := 0; i < len(ciphertext)/8; i++ {
		curCipher := ciphertext[i*8 : i*8+8]
		cipher.Decrypt(temp, xorBlock2(postWhiten, curCipher))
		curPlain := xorBlock3(prevXor, preWhiten, temp)
		out = append(out, curPlain...)
		copy(prevXor, curCipher)
	}

	return out, nil
}
Esempio n. 13
0
func DesEncrypt(src, key []byte) ([]byte, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		log.Printf("[des encrypt] NewCipher error, %v", err)
		return nil, err
	}

	bs := block.BlockSize()

	src = ZeroPadding(src, bs)
	// src = PKCS5Padding(src, bs)
	if len(src)%bs != 0 {
		return nil, errors.New("Need a multiple of the blocksize")
	}

	out := make([]byte, len(src))
	dst := out
	for len(src) > 0 {
		block.Encrypt(dst, src[:bs])
		src = src[bs:]
		dst = dst[bs:]
	}

	return out, nil

}
Esempio n. 14
0
func main() {
	key, _ := hex.DecodeString("0000000000000000")
	block, _ := des.NewCipher(key)
	data := make([]byte, 8)
	block.Encrypt(data, key)
	fmt.Println(hex.EncodeToString(data))
}
Esempio n. 15
0
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)
}
Esempio n. 16
0
func decryptDES(src, key, privParam []byte) (dst []byte, err error) {

	if len(src)%des.BlockSize != 0 {
		err = ArgumentError{
			Value:   len(src),
			Message: "Invalid DES cipher length",
		}
		return
	}
	if len(privParam) != 8 {
		err = ArgumentError{
			Value:   len(privParam),
			Message: "Invalid DES PrivParameter length",
		}
		return
	}

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

	iv := xor(key[8:16], privParam)
	dst = make([]byte, len(src))

	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(dst, src)
	return
}
func main() {
	c, err := des.NewCipher([]byte("32129232"))
	if err != nil {
		panic(err)
	}

	message := bytes.NewBufferString("this isn't a really secret, do you know that? no secret is best secret.")

	fmt.Println("original bytes:")
	fmt.Println([]byte(message.String()))

	encrypted := bytes.NewBuffer(nil)

	// var encrypted bytes.Buffer

	b8 := make([]byte, 8)

	w := cipher.StreamWriter{S: cipher.NewOFB(c, b8), W: encrypted}

	io.Copy(w, message)

	fmt.Println("encrypted bytes:")
	fmt.Println(encrypted.Bytes())

	encryptedOutput := fmt.Sprintf("%02x", encrypted.Bytes())

	fmt.Println(encryptedOutput)

	digital := fmt.Sprintf("%x", []byte("that's cool!"))

	var m []byte
	fmt.Sscanf(digital, "%x", &m)

	fmt.Println(string(m))

	c2, err := des.NewCipher([]byte("32129232"))

	w2 := cipher.StreamReader{S: cipher.NewOFB(c2, b8), R: encrypted}

	decrypted_message := bytes.NewBuffer(nil)

	io.Copy(decrypted_message, w2)

	fmt.Println(decrypted_message.String())

}
Esempio n. 18
0
func DecryptDESCBC(dst, src, key, iv []byte) error {
	desBlockEncrypter, err := des.NewCipher([]byte(key))
	if err != nil {
		return err
	}
	desDecrypter := cipher.NewCBCDecrypter(desBlockEncrypter, iv)
	desDecrypter.CryptBlocks(dst, src)
	return nil
}
Esempio n. 19
0
func encryptDes(key []byte, cleartext []byte, ciphertext []byte) {
	var desKey [8]byte
	createDesKey(key, desKey[:])
	cipher, err := des.NewCipher(desKey[:])
	if err != nil {
		panic(err)
	}
	cipher.Encrypt(ciphertext, cleartext)
}
Esempio n. 20
0
func calcLanManResponse(nonce [8]byte, password string) [24]byte {
	var lmpass [14]byte
	var key [16]byte
	var hash [21]byte

	copy(lmpass[:14], []byte(strings.ToUpper(password)))

	des56To64(key[:8], lmpass[:7])
	des56To64(key[8:], lmpass[7:])

	blk, _ := des.NewCipher(key[:8])
	blk.Encrypt(hash[:8], []byte("KGS!@#$%"))

	blk, _ = des.NewCipher(key[8:])
	blk.Encrypt(hash[8:], []byte("KGS!@#$%"))

	return calcNTLMResponse(nonce, hash)
}
Esempio n. 21
0
func NewDesConn(conn net.Conn, key []byte, iv []byte) (sc net.Conn, err error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return
	}
	in := cipher.NewCFBDecrypter(block, iv)
	out := cipher.NewCFBEncrypter(block, iv)
	return CryptConn{conn.(*net.TCPConn), in, out}, nil
}
Esempio n. 22
0
func calcNTLMResponse(nonce [8]byte, hash [21]byte) [24]byte {
	var ret [24]byte
	var key [24]byte

	des56To64(key[:8], hash[:7])
	des56To64(key[8:16], hash[7:14])
	des56To64(key[16:], hash[14:])

	blk, _ := des.NewCipher(key[:8])
	blk.Encrypt(ret[:8], nonce[:])

	blk, _ = des.NewCipher(key[8:16])
	blk.Encrypt(ret[8:16], nonce[:])

	blk, _ = des.NewCipher(key[16:])
	blk.Encrypt(ret[16:], nonce[:])

	return ret
}
Esempio n. 23
0
func NewDESCFBCipher(rwc io.ReadWriteCloser, password []byte) (*DESCFBCipher, error) {
	block, err := des.NewCipher(password)
	if err != nil {
		return nil, err
	}
	return &DESCFBCipher{
		block: block,
		rwc:   rwc,
	}, nil
}
Esempio n. 24
0
func (eci encryptedContentInfo) decrypt(key []byte) ([]byte, error) {
	alg := eci.ContentEncryptionAlgorithm.Algorithm
	if !alg.Equal(oidEncryptionAlgorithmDESCBC) && !alg.Equal(oidEncryptionAlgorithmDESEDE3CBC) && !alg.Equal(oidEncryptionAlgorithmAES256CBC) {
		fmt.Printf("Unsupported Content Encryption Algorithm: %s\n", alg)
		return nil, ErrUnsupportedAlgorithm
	}

	// EncryptedContent can either be constructed of multple OCTET STRINGs
	// or _be_ a tagged OCTET STRING
	var cyphertext []byte
	if eci.EncryptedContent.IsCompound {
		// Complex case to concat all of the children OCTET STRINGs
		var buf bytes.Buffer
		cypherbytes := eci.EncryptedContent.Bytes
		for {
			var part []byte
			cypherbytes, _ = asn1.Unmarshal(cypherbytes, &part)
			buf.Write(part)
			if cypherbytes == nil {
				break
			}
		}
		cyphertext = buf.Bytes()
	} else {
		// Simple case, the bytes _are_ the cyphertext
		cyphertext = eci.EncryptedContent.Bytes
	}

	var block cipher.Block
	var err error

	switch {
	case alg.Equal(oidEncryptionAlgorithmDESCBC):
		block, err = des.NewCipher(key)
	case alg.Equal(oidEncryptionAlgorithmDESEDE3CBC):
		block, err = des.NewTripleDESCipher(key)
	case alg.Equal(oidEncryptionAlgorithmAES256CBC):
		block, err = aes.NewCipher(key)
	}
	if err != nil {
		return nil, err
	}

	iv := eci.ContentEncryptionAlgorithm.Parameters.Bytes
	if len(iv) != block.BlockSize() {
		return nil, errors.New("pkcs7: encryption algorithm parameters are malformed")
	}
	mode := cipher.NewCBCDecrypter(block, iv)
	plaintext := make([]byte, len(cyphertext))
	mode.CryptBlocks(plaintext, cyphertext)
	if plaintext, err = unpad(plaintext, mode.BlockSize()); err != nil {
		return nil, err
	}
	return plaintext, nil
}
Esempio n. 25
0
// Create Response for comparison
func ntChallengeResponse(challenge []byte, passHash []byte) ([]byte, error) {
	// Pass is already encoded (NTPasswordHash)
	// ChallengeResponse
	res := make([]byte, 24)
	zPasswordHash := make([]byte, 21)

	// Set ZPasswordHash to PasswordHash zero-padded to 21 octets
	for i := 0; i < len(passHash); i++ {
		zPasswordHash[i] = passHash[i]
	}

	// DesEncrypt first 7 bytes
	{
		block, e := des.NewCipher(strToKey(zPasswordHash[:7]))
		if e != nil {
			return nil, e
		}
		mode := newECBEncrypter(block)
		mode.CryptBlocks(res, challenge)
	}

	// DesEncrypt second 7 bytes
	{
		block, e := des.NewCipher(strToKey(zPasswordHash[7:14]))
		if e != nil {
			return nil, e
		}
		mode := newECBEncrypter(block)
		mode.CryptBlocks(res[8:], challenge)
	}

	// DesEncrypt last 7 bytes
	{
		block, e := des.NewCipher(strToKey(zPasswordHash[14:]))
		if e != nil {
			return nil, e
		}
		mode := newECBEncrypter(block)
		mode.CryptBlocks(res[16:], challenge)
	}
	return res, nil
}
Esempio n. 26
0
func DesDecrypt(crypted, key []byte) ([]byte, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockMode := cipher.NewCBCDecrypter(block, key)
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	return origData, nil
}
Esempio n. 27
0
func (sp *UsmSecurityParameters) encryptPacket(scopedPdu []byte) ([]byte, error) {
	var b []byte

	var privkey = genlocalkey(sp.AuthenticationProtocol,
		sp.PrivacyPassphrase,
		sp.AuthoritativeEngineID)

	switch sp.PrivacyProtocol {
	case AES:
		var iv [16]byte
		binary.BigEndian.PutUint32(iv[:], sp.AuthoritativeEngineBoots)
		binary.BigEndian.PutUint32(iv[4:], sp.AuthoritativeEngineTime)
		copy(iv[8:], sp.PrivacyParameters)

		block, err := aes.NewCipher(privkey[:16])
		if err != nil {
			return nil, err
		}
		stream := cipher.NewCFBEncrypter(block, iv[:])
		ciphertext := make([]byte, len(scopedPdu))
		stream.XORKeyStream(ciphertext, scopedPdu)
		pduLen, err := marshalLength(len(ciphertext))
		if err != nil {
			return nil, err
		}
		b = append([]byte{byte(OctetString)}, pduLen...)
		scopedPdu = append(b, ciphertext...)
	default:
		preiv := privkey[8:]
		var iv [8]byte
		for i := 0; i < len(iv); i++ {
			iv[i] = preiv[i] ^ sp.PrivacyParameters[i]
		}
		block, err := des.NewCipher(privkey[:8])
		if err != nil {
			return nil, err
		}
		mode := cipher.NewCBCEncrypter(block, iv[:])

		pad := make([]byte, des.BlockSize-len(scopedPdu)%des.BlockSize)
		scopedPdu = append(scopedPdu, pad...)

		ciphertext := make([]byte, len(scopedPdu))
		mode.CryptBlocks(ciphertext, scopedPdu)
		pduLen, err := marshalLength(len(ciphertext))
		if err != nil {
			return nil, err
		}
		b = append([]byte{byte(OctetString)}, pduLen...)
		scopedPdu = append(b, ciphertext...)
	}

	return scopedPdu, nil
}
Esempio n. 28
0
func desHash(clear []byte) ([]byte, error) {
	block, e := des.NewCipher(strToKey(clear)) // clear=secret
	if e != nil {
		return nil, e
	}

	res := make([]byte, 8)
	mode := newECBEncrypter(block)
	mode.CryptBlocks(res, []byte(`KGS!@#$%`))
	return res, nil
}
func E(key, plaintext []byte) []byte {
	cipher, err := des.NewCipher(key)
	if err != nil {
		fmt.Println("ERROR: failed to create DES cipher.", err)
		os.Exit(1)
	}

	ciphertext := make([]byte, len(plaintext))
	cipher.Encrypt(ciphertext, plaintext)
	return ciphertext
}
Esempio n. 30
-1
func encryptDESCBC(content []byte) ([]byte, *encryptedContentInfo, error) {
	// Create DES key & CBC IV
	key := make([]byte, 8)
	iv := make([]byte, des.BlockSize)
	_, err := rand.Read(key)
	if err != nil {
		return nil, nil, err
	}
	_, err = rand.Read(iv)
	if err != nil {
		return nil, nil, err
	}

	// Encrypt padded content
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, nil, err
	}
	mode := cipher.NewCBCEncrypter(block, iv)
	plaintext, err := pad(content, mode.BlockSize())
	cyphertext := make([]byte, len(plaintext))
	mode.CryptBlocks(cyphertext, plaintext)

	// Prepare ASN.1 Encrypted Content Info
	eci := encryptedContentInfo{
		ContentType: oidData,
		ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{
			Algorithm:  oidEncryptionAlgorithmDESCBC,
			Parameters: asn1.RawValue{Tag: 4, Bytes: iv},
		},
		EncryptedContent: marshalEncryptedContent(cyphertext),
	}

	return key, &eci, nil
}