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 } } }
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 ExampleNewOFB() { key := []byte("example key 1234") plaintext := []byte("some plaintext") block, err := aes.NewCipher(key) if err != nil { panic(err) } // The IV needs to be unique, but not secure. Therefore it's common to // include it at the beginning of the ciphertext. ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { panic(err) } stream := cipher.NewOFB(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) // It's important to remember that ciphertexts must be authenticated // (i.e. by using crypto/hmac) as well as being encrypted in order to // be secure. // OFB mode is the same for both encryption and decryption, so we can // also decrypt that ciphertext with NewOFB. plaintext2 := make([]byte, len(plaintext)) stream = cipher.NewOFB(block, iv) stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:]) fmt.Printf("%s\n", plaintext2) // Output: some plaintext }
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.NewOFB(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.NewOFB(block, cipherText[:aes.BlockSize]) decryptStream.XORKeyStream(decryptedText, cipherText[aes.BlockSize:]) fmt.Printf("Decrypted text: %s\n", string(decryptedText)) }
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 }
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 }
func AesEncryptData(data, key []byte, ctp string) []byte { block, err := aes.NewCipher(key) if err != nil { return nil } // The IV needs to be unique, but not secure. Therefore it's common to // include it at the beginning of the ciphertext. data_enc := make([]byte, aes.BlockSize+len(data)) iv := data_enc[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return nil } var stream cipher.Stream switch ctp { case "cfb": stream = cipher.NewCFBEncrypter(block, iv) case "ctr": stream = cipher.NewCTR(block, iv) default: stream = cipher.NewOFB(block, iv) } stream.XORKeyStream(data_enc[aes.BlockSize:], data) // It's important to remember that ciphertexts must be authenticated // (i.e. by using crypto/hmac) as well as being encrypted in order to // be secure. return data_enc }
// WriteBytes writes an encrypted/compressed stream to an io.Writer func writeBytes(out io.Writer, key string, data []byte) error { var gzWriter *gzip.Writer // compressed writer var iv [aes.BlockSize]byte // initialization vector var cb cipher.Block // cipher block interface var err error // general error holder // init cipher block if cb, err = aes.NewCipher(hashKey(key)); err != nil { return err } // init encrypted writer encWriter := &cipher.StreamWriter{ S: cipher.NewOFB(cb, iv[:]), W: out, } // close when done defer encWriter.Close() // wrap encrypted writer gzWriter = gzip.NewWriter(encWriter) // close when done defer gzWriter.Close() // copy data to destination file compressing and encrypting along the way _, err = io.Copy(gzWriter, bytes.NewReader(data)) // return copy error return err }
// decrypt file func (c *Crypt) DecryptFile(encrypt, decrypt string) error { inFile, err := os.Open(encrypt) if err != nil { return err } defer inFile.Close() block, err := aes.NewCipher(c.key) if err != nil { return err } // If the key is unique for each ciphertext, then it's ok to use a zero // IV. var iv [aes.BlockSize]byte stream := cipher.NewOFB(block, iv[:]) outFile, err := os.OpenFile(decrypt, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return err } defer outFile.Close() 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 } return nil }
func (a *BuyActivity) decryptResult() error { block, err := aes.NewCipher(a.encResultKey[:]) if err != nil { return err } temp := a.manager.GetStorage().Create(fmt.Sprintf("Buy #%v: result", a.GetKey())) defer temp.Dispose() encrypted := a.encResultFile.Open() defer encrypted.Close() // Create OFB stream with null initialization vector (ok for one-time key) var iv [aes.BlockSize]byte stream := cipher.NewOFB(block, iv[:]) reader := &cipher.StreamReader{S: stream, R: encrypted} _, err = io.Copy(temp, reader) if err != nil { return err } if err := temp.Close(); err != nil { return err } a.resultFile = temp.File() return nil }
// NewReader returns a reader that encrypts or decrypts its input stream. func (key TwofishKey) NewReader(r io.Reader) io.Reader { // OK to use a zero IV if the key is unique for each ciphertext. iv := make([]byte, twofish.BlockSize) stream := cipher.NewOFB(key.NewCipher(), iv) return &cipher.StreamReader{S: stream, R: r} }
// readBytes reads an encrypted/compressed steam from an io.Reader // and returns a decoded byte slice func readBytes(in io.Reader, key string) ([]byte, error) { var gzReader *gzip.Reader // compressed reader var iv [aes.BlockSize]byte // initialization vector var cb cipher.Block // cipher block interface var outBytes *bytes.Buffer // output buffer var err error // general error handler // init cipher block if cb, err = aes.NewCipher(hashKey(key)); err != nil { return nil, err } // init encrypted reader encReader := &cipher.StreamReader{ S: cipher.NewOFB(cb, iv[:]), R: in, } // wrap encrypted reader if gzReader, err = gzip.NewReader(encReader); err != nil { return nil, err } // close when done defer gzReader.Close() // init output outBytes = new(bytes.Buffer) // read data into output buffer decompressing and decrypting along the way _, err = io.Copy(outBytes, gzReader) // return bytes and last error state return outBytes.Bytes(), err }
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 }
// 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 }
// encryptAES enrypts plaintext input with passed key, IV and mode in AES block cipher; // and returns ciphertext output func encryptAES(input []byte, output []byte, key, iv []byte, mode Mode) error { block, err := aes.NewCipher(key) if err != nil { return errors.New("Couldn't create block cipher.") } // Prepend IV to ciphertext. // Generate IV randomly if it is not passed if iv == nil { if iv = generateIV(aes.BlockSize); iv == nil { return errors.New("Couldn't create random initialization vector (IV).") } } copy(output, iv) switch mode { case CBC: if len(input)%aes.BlockSize != 0 { input = addPadding(input, aes.BlockSize) } mode := cipher.NewCBCEncrypter(block, iv) mode.CryptBlocks(output[aes.BlockSize:], input) case CFB: mode := cipher.NewCFBEncrypter(block, iv) mode.XORKeyStream(output[aes.BlockSize:], input) case CTR: mode := cipher.NewCTR(block, iv) mode.XORKeyStream(output[aes.BlockSize:], input) case OFB: mode := cipher.NewOFB(block, iv) mode.XORKeyStream(output[aes.BlockSize:], input) } return nil }
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 }
func (s *session) setKey(inkey, outkey []byte) error { block, err := aes.NewCipher(inkey) if err != nil { return err } var iniv [aes.BlockSize]byte s.r = cipher.StreamReader{S: cipher.NewOFB(block, iniv[:]), R: s.r} block, err = aes.NewCipher(outkey) if err != nil { return err } var outiv [aes.BlockSize]byte s.w = cipher.StreamWriter{S: cipher.NewOFB(block, outiv[:]), W: s.w} return nil }
func getDecryptStream(passphrase string, iv []byte) (stream cipher.Stream, err error) { enc_block, err := aes.NewCipher(getEncryptKey(passphrase)) if err != nil { return } stream = cipher.NewOFB(enc_block, iv) return }
// bad example OMIT // Example using AES func One(plaintext io.Reader, key []byte) (io.Reader, error) { blk, err := aes.NewCipher(key) if err != nil { return nil, err } iv := make([]byte, blk.BlockSize()) // HLcallout return cipher.StreamReader{S: cipher.NewOFB(blk, iv), R: plaintext}, nil // HLcallout }
func AesReadCloserWrapper(key string, r io.Reader) (io.ReadCloser, error) { c, err := aes.NewCipher([]byte(key)) if err != nil { return nil, fmt.Errorf("fail to get cipher block: %v", err) } var iv [aes.BlockSize]byte return &StreamReadCloser{S: cipher.NewOFB(c, iv[:]), R: r}, nil }
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()) }
// CipherStreamReader 对数据流进行加密 func CipherStreamReader(skey string, encodeURL string, reader io.Reader) *cipher.StreamReader { key := strMd5(fmt.Sprintf("%s#kxsw#%s", skey, encodeURL)) block, err := aes.NewCipher(key) if err != nil { panic(err) } var iv [aes.BlockSize]byte stream := cipher.NewOFB(block, iv[:]) return &cipher.StreamReader{S: stream, R: reader} }
// Encrypts data to destrination writer func Encrypt(dst io.Writer, data *bytes.Buffer, key, iv []byte) (err error) { c, err := aes.NewCipher(key) if err != nil { return } w := &cipher.StreamWriter{S: cipher.NewOFB(c, iv), W: dst} io.Copy(w, data) return }
// Returns decrypted data from src reader func Decrypt(src io.Reader, key, iv []byte) (data *bytes.Buffer, err error) { c, err := aes.NewCipher(key) if err != nil { return } r := &cipher.StreamReader{S: cipher.NewOFB(c, iv), R: src} data = new(bytes.Buffer) io.Copy(data, r) return }
func (c *Cryptor) setStream(key []byte) error { block, err := aes.NewCipher(key) if err != nil { return err } var iv [aes.BlockSize]byte c.stream = cipher.NewOFB(block, iv[:]) return nil }
func createCipher(password string, iv []byte) (cipher.Stream, error) { passwordHash := sha256.Sum256(bytes.NewBufferString(password).Bytes()) blockCipher, err := aes.NewCipher(passwordHash[:]) if err != nil { return nil, err } streamCipher := cipher.NewOFB(blockCipher, iv) return streamCipher, nil }
func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) { r, _ := os.Open(srcfile) var w io.Writer w, _ = os.Create(dstfile) c, err := aes.NewCipher(key) if err != nil { log.Fatal(err) } w = &cipher.StreamWriter{S: cipher.NewOFB(c, iv), W: w} io.Copy(w, r) }
func NewAESEncrypter(block cipher.Block, iv []byte) (cipher.Stream, error) { aes := block.(*aesNativeCipher) switch aes.mode & 0xff { case MODE_OFB: return cipher.NewOFB(aes, iv), nil case MODE_CFB: return cipher.NewCFBDecrypter(block, iv), nil case MODE_CTR: return cipher.NewCTR(block, iv), nil } return nil, ERR_NOT_IMPLEMENTED }
func DecryptAndGunzip(dstfile, srcfile string, key, iv []byte) { f, _ := os.Open(srcfile) defer f.Close() c, err := aes.NewCipher(key) if err != nil { log.Fatal(err) } r := &cipher.StreamReader{S: cipher.NewOFB(c, iv), R: f} w, _ := os.Create(dstfile) defer w.Close() io.Copy(w, r) }
func (a *SellActivity) dispatchWorkAndSaveEncryptedResult(log bitwrk.Logger, workFile cafs.File) error { // Watch transaction state and close connection to worker when transaction expires connChan := make(chan io.Closer) exitChan := make(chan bool) go a.watchdog(log, exitChan, connChan, func() bool { return a.tx.State == bitwrk.StateActive }) defer func() { exitChan <- true }() st := NewScopedTransport() connChan <- st defer st.Close() reader := workFile.Open() defer reader.Close() result, err := a.worker.DoWork(reader, NewClient(&st.Transport)) if err != nil { return err } defer result.Close() temp := a.manager.storage.Create(fmt.Sprintf("Sell #%v: encrypted result", a.GetKey())) defer temp.Dispose() // Use AES-256 to encrypt the result block, err := aes.NewCipher(a.encResultKey[:]) if err != nil { return err } // Create OFB stream with null initialization vector (ok for one-time key) var iv [aes.BlockSize]byte stream := cipher.NewOFB(block, iv[:]) writer := &cipher.StreamWriter{S: stream, W: temp} _, err = io.Copy(writer, result) if err != nil { return err } if err := temp.Close(); err != nil { return err } if err := result.Close(); err != nil { return err } a.execSync(func() { a.encResultFile = temp.File() }) return nil }