本文整理汇总了Golang中crypto/sha1.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewConnWithHash
func NewConnWithHash(conn *net.TCPConn) *hashedConn {
return &hashedConn{
Conn: NewConn(conn, nullCipherKit),
rHash: sha1.New(),
wHash: sha1.New(),
}
}
示例2: TestTable_SymmeticsHash
func TestTable_SymmeticsHash(t *testing.T) {
ft := NewTable()
GenerateTestFlows(t, ft, 0xca55e77e, "probe")
foundLayers := make(map[string]bool)
for _, f := range ft.GetFlows() {
hasher := sha1.New()
for _, ep := range f.GetStatistics().GetEndpoints() {
hasher.Write(ep.Hash)
}
layersH := hex.EncodeToString(hasher.Sum(nil))
foundLayers[layersH] = true
}
ft2 := NewTable()
GenerateTestFlowsSymmetric(t, ft2, 0xca55e77e, "probe")
for _, f := range ft2.GetFlows() {
hasher := sha1.New()
for _, ep := range f.GetStatistics().GetEndpoints() {
hasher.Write(ep.Hash)
}
layersH := hex.EncodeToString(hasher.Sum(nil))
if _, found := foundLayers[layersH]; !found {
t.Errorf("hash endpoint should be symmeticaly, not found : %s", layersH)
t.Fail()
}
}
}
示例3: NewSessionHandler
func NewSessionHandler(handler http.Handler, key string, rs *RequestSessions) *SessionHandler {
// sha1 sums are 20 bytes long. we use the first 16 bytes as
// the aes key.
encHash := sha1.New()
encHash.Write([]byte(key))
encHash.Write([]byte("-encryption"))
hmacHash := sha1.New()
hmacHash.Write([]byte(key))
hmacHash.Write([]byte("-hmac"))
// if the user hasn't specified a session handler, use the
// package's default one
if rs == nil {
rs = Session
}
return &SessionHandler{
Handler: handler,
CookieName: "session",
CookiePath: "/",
RS: rs,
encKey: encHash.Sum(nil)[:blockSize],
hmacKey: hmacHash.Sum(nil)[:blockSize],
}
}
示例4: main
func main() {
TestString := "Hi,panda!"
Md5Inst := md5.New()
Md5Inst.Write([]byte(TestString))
Result := Md5Inst.Sum([]byte(""))
fmt.Printf("%x\n\n", Result)
Sha1Inst := sha1.New()
Sha1Inst.Write([]byte(TestString))
Result = Sha1Inst.Sum([]byte(""))
fmt.Printf("%x\n\n", Result)
TestFile := "123.txt"
infile, inerr := os.Open(TestFile)
if inerr == nil {
md5h := md5.New()
io.Copy(md5h, infile)
fmt.Printf("%x , %s \n", md5h.Sum([]byte("")), TestFile)
sha1h := sha1.New()
io.Copy(sha1h, infile)
fmt.Printf("%x ,%s \n", sha1h.Sum([]byte("")), TestFile)
} else {
fmt.Println(inerr)
os.Exit(1)
}
}
示例5: TestWriteReadLargeStreams
// TestWriteReadLargeStreams tests that a 5GB file may be written to the storage
// driver safely.
func (suite *DriverSuite) TestWriteReadLargeStreams(c *check.C) {
if testing.Short() {
c.Skip("Skipping test in short mode")
}
filename := randomPath(32)
defer suite.deletePath(c, firstPart(filename))
checksum := sha1.New()
var fileSize int64 = 5 * 1024 * 1024 * 1024
contents := newRandReader(fileSize)
written, err := suite.StorageDriver.WriteStream(suite.ctx, filename, 0, io.TeeReader(contents, checksum))
c.Assert(err, check.IsNil)
c.Assert(written, check.Equals, fileSize)
reader, err := suite.StorageDriver.ReadStream(suite.ctx, filename, 0)
c.Assert(err, check.IsNil)
defer reader.Close()
writtenChecksum := sha1.New()
io.Copy(writtenChecksum, reader)
c.Assert(writtenChecksum.Sum(nil), check.DeepEquals, checksum.Sum(nil))
}
示例6: Filehash
func Filehash(path_or string, file_or *os.File) (string, error) {
if (path_or != "" && file_or == nil) || (path_or == "" && file_or != nil) {
if path_or != "" && file_or == nil {
if file, err := os.Open(path_or); err != nil {
return "", err
} else {
defer file.Close()
h := sha1.New()
if _, erro := io.Copy(h, file); erro != nil {
return "", erro
} else {
result := hex.EncodeToString(h.Sum(nil))
return result, nil
}
}
} else {
h := sha1.New()
if _, erro := io.Copy(h, file_or); erro != nil {
return "", erro
} else {
result := hex.EncodeToString(h.Sum(nil))
return result, nil
}
}
}
return "", errors.New("没有参数无法生成hash,请输入文件路径 或 *os.File!")
}
示例7: New
// Create a new handler dumping data chunks and index info to db for an
// object/file identified by label.
func New(tx *sql.Tx, label string) (h *Handler, err error) {
// get next file/object id
var maxfid sql.NullInt64
row := tx.QueryRow(getMaxFidSql)
if err := row.Scan(&maxfid); err != nil {
return nil, err
}
// get next chunk rowid
var maxrow sql.NullInt64
row = tx.QueryRow(getMaxChunkRowSql)
if err := row.Scan(&maxrow); err != nil {
return nil, err
}
// config and return handler
h = &Handler{}
h.tx = tx
h.nextChunkRow = int(maxrow.Int64) + 1
h.label = label
h.fid = int(maxfid.Int64) + 1
h.fullH = sha1.New()
h.chunkH = sha1.New()
return h, nil
}
示例8: TestPad
func TestPad(t *testing.T) {
private, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil || private == nil {
t.Fatal("Can't gen private key %s\n", err)
}
public := &private.PublicKey
var a [9]byte
copy(a[0:8], "IDENTITY")
seed := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
encrypted_secret, err := rsa.EncryptOAEP(sha1.New(), rand.Reader,
public, seed, a[0:9])
if err != nil {
t.Fatal("Can't encrypt ", err)
}
fmt.Printf("encrypted_secret: %x\n", encrypted_secret)
decrypted_secret, err := rsa.DecryptOAEP(sha1.New(), rand.Reader,
private, encrypted_secret, a[0:9])
if err != nil {
t.Fatal("Can't decrypt ", err)
}
fmt.Printf("decrypted_secret: %x\n", decrypted_secret)
var N *big.Int
var D *big.Int
var x *big.Int
var z *big.Int
N = public.N
D = private.D
x = new(big.Int)
z = new(big.Int)
x.SetBytes(encrypted_secret)
z = z.Exp(x, D, N)
decrypted_pad := z.Bytes()
fmt.Printf("decrypted_pad : %x\n", decrypted_pad)
}
示例9: New
func (c Combination) New() []byte {
if len(c.Salt) == 0 {
c.Salt = generateSalt(c.Secret, 16)
}
salt := c.Salt
comb := c.Secret + string(salt)
fn := c.Func
var pwhash hash.Hash
switch fn {
case MD5:
pwhash = md5.New()
case SHA1:
pwhash = sha1.New()
case SHA256:
pwhash = sha256.New()
default:
pwhash = sha1.New()
}
io.WriteString(pwhash, comb)
return pwhash.Sum(nil)
}
示例10: NewConnWithHash
func NewConnWithHash(conn *net.TCPConn) *hashedConn {
return &hashedConn{
Conn: &Conn{Conn: conn, wlock: new(sync.Mutex)},
rHash: sha1.New(),
wHash: sha1.New(),
}
}
示例11: newFinishedHash
func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash {
var ret finishedHash
if version >= VersionTLS12 {
ret.hash = cipherSuite.hash()
ret.client = ret.hash.New()
ret.server = ret.hash.New()
if version == VersionTLS12 {
ret.prf = prf12(ret.hash.New)
}
} else {
ret.hash = crypto.MD5SHA1
ret.client = sha1.New()
ret.server = sha1.New()
ret.clientMD5 = md5.New()
ret.serverMD5 = md5.New()
ret.prf = prf10
}
ret.buffer = []byte{}
ret.version = version
return ret
}
示例12: Sign
// Sign generate sign for data with cert & private key
func Sign(data io.Reader, cert *x509.Certificate, priv *rsa.PrivateKey) ([]byte, error) {
var hash = sha1.New()
if _, err := io.Copy(hash, data); err != nil {
return nil, err
}
var signedData = signedData{
Version: 1,
DigestAlgorithms: []algorithmIdentifier{{
Algorithm: oidSHA1,
Parameters: asn1.RawValue{Tag: 5},
}},
ContentInfo: contentInfo{Type: oidPKCS7Data},
Certificates: asn1.RawValue{
Class: 2, Tag: 0, Bytes: append(wwdr, cert.Raw...), IsCompound: true,
},
SignerInfos: []signerInfo{{
Version: 1,
IssuerAndSerialNumber: issuerAndSerialNumber{
Issuer: asn1.RawValue{FullBytes: cert.RawIssuer},
SerialNumber: cert.SerialNumber,
},
DigestAlgorithm: algorithmIdentifier{
Algorithm: oidSHA1,
Parameters: asn1.RawValue{Tag: 5},
},
AuthenticatedAttributes: []attribute{
newAttribute(oidPKCS9ContentType, oidPKCS7Data),
newAttribute(oidPKCS9SigningTime, time.Now().UTC()),
newAttribute(oidPKCS9MessageDigest, hash.Sum(nil)),
},
DigestEncryptionAlgorithm: algorithmIdentifier{
Algorithm: oidPKCS1RSAEncryption,
Parameters: asn1.RawValue{Tag: 5},
},
}},
}
encodedAuthenticatedAttributes, err := asn1.Marshal(
signedData.SignerInfos[0].AuthenticatedAttributes)
if err != nil {
return nil, err
}
// For the digest of the authenticated attributes, we need a
// slightly different encoding. Change the attributes from a
// SEQUENCE to a SET.
var originalFirstByte = encodedAuthenticatedAttributes[0]
encodedAuthenticatedAttributes[0] = 0x31
hash = sha1.New()
hash.Write(encodedAuthenticatedAttributes)
var attributesDigest = hash.Sum(nil)
encodedAuthenticatedAttributes[0] = originalFirstByte
encryptedDigest, err := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA1, attributesDigest)
if err != nil {
return nil, err
}
signedData.SignerInfos[0].EncryptedDigest = encryptedDigest
return asn1.Marshal(container{
OID: oidPKCS7SignedData,
SignedData: signedData,
})
}
示例13: TestSiteBuilderBuildFormatsSources
func TestSiteBuilderBuildFormatsSources(t *testing.T) {
mkTestSite()
if noCleanup {
fmt.Println("tmpdir =", tmpdir)
} else {
defer rmTmpDir()
}
sb, err := newSiteBuilder(&SiteBuilderCfg{
WwwRoot: testWwwRoot,
OutputGopath: tmpdir,
GenServerBind: ":9182",
Format: true,
MkOutDir: true,
Compile: false,
})
if err != nil {
t.Error(err)
return
}
err = sb.Build()
if err != nil {
t.Error(err)
return
}
fileName := path.Join(aspenGoGenDir, "shill-SLASH-cans-DOT-txt.go")
fileContent, err := ioutil.ReadFile(fileName)
if err != nil {
t.Error(err)
return
}
firstHash := sha1.New()
io.WriteString(firstHash, string(fileContent))
firstSum := fmt.Sprintf("%x", firstHash.Sum(nil))
err = formatAspenGoGen()
if err != nil {
t.Error(err)
return
}
fileContent, err = ioutil.ReadFile(fileName)
if err != nil {
t.Error(err)
return
}
secondHash := sha1.New()
io.WriteString(secondHash, string(fileContent))
secondSum := fmt.Sprintf("%x", secondHash.Sum(nil))
if firstSum != secondSum {
t.Errorf("Hash for %q changed!", fileName)
}
}
示例14: getUserHash
func getUserHash(salt []byte, user string, password string) *big.Int {
hash1 := sha1.New()
hash1.Write(bytes.NewBufferString(user + ":" + password).Bytes())
hash2 := sha1.New()
hash2.Write(salt)
hash2.Write(hash1.Sum(nil))
return bytesToBig(hash2.Sum(nil))
}
示例15: Close
// Close finishes writing the APK. This includes writing the manifest and
// signing the archive, and writing the ZIP central directory.
//
// It does not close the underlying writer.
func (w *Writer) Close() error {
if err := w.clearCur(); err != nil {
return fmt.Errorf("apk: %v", err)
}
manifest := new(bytes.Buffer)
fmt.Fprint(manifest, manifestHeader)
certBody := new(bytes.Buffer)
for _, entry := range w.manifest {
n := entry.name
h := base64.StdEncoding.EncodeToString(entry.sha1.Sum(nil))
fmt.Fprintf(manifest, "Name: %s\nSHA1-Digest: %s\n\n", n, h)
cHash := sha1.New()
fmt.Fprintf(cHash, "Name: %s\r\nSHA1-Digest: %s\r\n\r\n", n, h)
ch := base64.StdEncoding.EncodeToString(cHash.Sum(nil))
fmt.Fprintf(certBody, "Name: %s\nSHA1-Digest: %s\n\n", n, ch)
}
mHash := sha1.New()
mHash.Write(manifest.Bytes())
cert := new(bytes.Buffer)
fmt.Fprint(cert, certHeader)
fmt.Fprintf(cert, "SHA1-Digest-Manifest: %s\n\n", base64.StdEncoding.EncodeToString(mHash.Sum(nil)))
cert.Write(certBody.Bytes())
mw, err := w.Create("META-INF/MANIFEST.MF")
if err != nil {
return err
}
if _, err := mw.Write(manifest.Bytes()); err != nil {
return fmt.Errorf("apk: %v", err)
}
cw, err := w.Create("META-INF/CERT.SF")
if err != nil {
return err
}
if _, err := cw.Write(cert.Bytes()); err != nil {
return fmt.Errorf("apk: %v", err)
}
rsa, err := signPKCS7(rand.Reader, w.priv, cert.Bytes())
if err != nil {
return fmt.Errorf("apk: %v", err)
}
rw, err := w.Create("META-INF/CERT.RSA")
if err != nil {
return err
}
if _, err := rw.Write(rsa); err != nil {
return fmt.Errorf("apk: %v", err)
}
return w.w.Close()
}