我试图流式传输AES加密的视频文件;但是我们需要在通过http
传输它之前动态解密它如何将解密数据的输出写入http writer
package main
import (
"crypto/aes"
"crypto/cipher"
"io"
"log"
"net/http"
"os"
)
var key []byte = []byte("yourAESPrivateKey")
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
inFile, err := os.Open("2.ts")
if err != nil {
log.Fatal(err)
}
defer inFile.Close()
block, err := aes.NewCipher(key)
if err != nil {
log.Fatal(err)
return
}
var iv [aes.BlockSize]byte
stream := cipher.NewOFB(block, iv[:])
w.Header().Set("Content-type", "video/mp4")
writer := &cipher.StreamWriter{S: stream, W: w}
if _, err := io.Copy(writer, inFile); err != nil {
log.Fatal(err)
return
}
//http.ServeContent(w, r, "video.mp4", time.Now(), inFile)
}
func main() {
http.HandleFunc("/", ServeHTTP)
http.ListenAndServe(":2020", nil)
}
答案 0 :(得分:0)
我增强了我的代码
所以,如果我请求加密文件,服务器将解密它并正确地提供它,但是我有另外一个问题,如下所示
现在的问题是,如果文件超过一定的大小,我会收到损坏的文件。
我已经对文本文件进行了一些测试以进行调试,所以我可以在这里发布数据结果(big corrupted file)检查文件的结尾
package main
import (
"crypto/aes"
"crypto/cipher"
"log"
"net/http"
"os"
"time"
)
type cipherHttpWriter struct {
http.ResponseWriter
}
func (c cipherHttpWriter) Write(b []byte) (int, error) {
var key []byte = []byte("we!@09bsa$.a-ala.HJOqweK45aghf&A")
block, err := aes.NewCipher(key)
if err != nil {
return 0, err
}
var iv [aes.BlockSize]byte
stream := cipher.NewOFB(block, iv[:])
streamWriter := &cipher.StreamWriter{S: stream, W: c.ResponseWriter}
defer streamWriter.Close()
return streamWriter.Write(b)
}
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
inFile, err := os.Open(string(r.URL.Path[1:]))
if err != nil {
log.Fatal(err)
}
defer inFile.Close()
writer := cipherHttpWriter{}
writer.ResponseWriter = w
http.ServeContent(writer, r, "", time.Now(), inFile)
}
func main() {
http.HandleFunc("/", ServeHTTP)
http.ListenAndServe(":2020", nil)
}