如何在golang中动态切换哈希算法?

huangapple go评论76阅读模式
英文:

How to dynamically switch between hash algorithms in golang?

问题

我想根据调用者的输入能够在哈希算法之间进行切换,例如,实现一个函数:

func GenericHash(dat []byte, hash unint) (string, error) { ... }

其中,hash 是由 crypto.Hash 指定的算法类型。

我不确定如何编写这个函数,特别是 import 语句应该放在哪里。如果我在顶部包含所有我将使用的算法的 import 语句,Go 会抱怨它们被导入但未使用。有没有办法按需导入?

英文:

I want to be able to switch between hash algorithms depending on caller input, for example, implement a function:

func GenericHash(dat []byte, hash unint) (string, error) { ... }

where hash is the algorithm type as specified by crypto.Hash.

I'm not sure how to write this function, in particular, where the import statements should go. If I include all the import statements for algorithms that I will use at the top, go complains that they're imported and not used. Is there anyway to import on demand?

答案1

得分: 6

你需要做的是仅导入包的副作用(即在导入包时使用空白标识符)。这意味着导入的包的init函数将被执行,但你将无法直接访问它们导出的成员。

以下是解决问题的一种方法:

import (
  "errors"
  "encoding/hex"
  "crypto"
  _ "crypto/md5"
  _ "crypto/sha1"
  // 导入更多哈希包
)

func GenericHash(dat []byte, hash crypto.Hash) (string, error) {
  if !hash.Available() {
    return "", errors.New("哈希不可用")
  }
  h := hash.New()
  return hex.EncodeToString(h.Sum(dat)), nil
}
英文:

What you need to do is import the packages for their side effects only (i.e. use the blank identifier when importing the packages). This means that the imported packages' init functions will be executed, but you will not be able to access any of their exported members directly.

Here is one way you could solve your problem:

import (
  "errors"
  "encoding/hex"
  "crypto"
  _ "crypto/md5"
  _ "crypto/sha1"
  // import more hash packages
)

func GenericHash(dat []byte, hash crypto.Hash) (string, error) {
  if !hash.Available() {
    return "", errors.New("hash unavailable")
  }
  h := hash.New()
  return hex.EncodeToString(h.Sum(dat)), nil
}

huangapple
  • 本文由 发表于 2015年9月17日 07:19:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/32620290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定