本文整理匯總了Golang中crypto.Signer類的典型用法代碼示例。如果您正苦於以下問題:Golang Signer類的具體用法?Golang Signer怎麽用?Golang Signer使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Signer類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: jwsEncodeJSON
// jwsEncodeJSON signs claimset using provided key and a nonce.
// The result is serialized in JSON format.
// See https://tools.ietf.org/html/rfc7515#section-7.
func jwsEncodeJSON(claimset interface{}, key crypto.Signer, nonce string) ([]byte, error) {
jwk, err := jwkEncode(key.Public())
if err != nil {
return nil, err
}
phead := fmt.Sprintf(`{"alg":"RS256","jwk":%s,"nonce":%q}`, jwk, nonce)
phead = base64.RawURLEncoding.EncodeToString([]byte(phead))
cs, err := json.Marshal(claimset)
if err != nil {
return nil, err
}
payload := base64.RawURLEncoding.EncodeToString(cs)
h := sha256.New()
h.Write([]byte(phead + "." + payload))
sig, err := key.Sign(rand.Reader, h.Sum(nil), crypto.SHA256)
if err != nil {
return nil, err
}
enc := struct {
Protected string `json:"protected"`
Payload string `json:"payload"`
Sig string `json:"signature"`
}{
Protected: phead,
Payload: payload,
Sig: base64.RawURLEncoding.EncodeToString(sig),
}
return json.Marshal(&enc)
}
示例2: jwsEncodeJSON
// jwsEncodeJSON signs claimset using provided key and a nonce.
// The result is serialized in JSON format.
// See https://tools.ietf.org/html/rfc7515#section-7.
func jwsEncodeJSON(claimset interface{}, key crypto.Signer, nonce string) ([]byte, error) {
jwk, err := jwkEncode(key.Public())
if err != nil {
return nil, err
}
alg, sha := jwsHasher(key)
if alg == "" || !sha.Available() {
return nil, ErrUnsupportedKey
}
phead := fmt.Sprintf(`{"alg":%q,"jwk":%s,"nonce":%q}`, alg, jwk, nonce)
phead = base64.RawURLEncoding.EncodeToString([]byte(phead))
cs, err := json.Marshal(claimset)
if err != nil {
return nil, err
}
payload := base64.RawURLEncoding.EncodeToString(cs)
hash := sha.New()
hash.Write([]byte(phead + "." + payload))
sig, err := jwsSign(key, sha, hash.Sum(nil))
if err != nil {
return nil, err
}
enc := struct {
Protected string `json:"protected"`
Payload string `json:"payload"`
Sig string `json:"signature"`
}{
Protected: phead,
Payload: payload,
Sig: base64.RawURLEncoding.EncodeToString(sig),
}
return json.Marshal(&enc)
}
示例3: Add
// Add adds a new key to the server's internal repertoire.
// Stores in maps by SKI and (if possible) Digest, SNI, Server IP, and Client IP.
func (keys *defaultKeystore) Add(op *gokeyless.Operation, priv crypto.Signer) error {
ski, err := gokeyless.GetSKI(priv.Public())
if err != nil {
return err
}
keys.Lock()
defer keys.Unlock()
if digest, err := gokeyless.GetDigest(priv.Public()); err == nil {
keys.digests[digest] = ski
}
if op != nil {
if op.SNI != "" {
keys.snis[op.SNI] = ski
}
if op.ServerIP != nil {
keys.serverIPs[op.ServerIP.String()] = ski
}
if op.ClientIP != nil {
keys.clientIPs[op.ClientIP.String()] = ski
}
keys.validAKIs[ski] = keys.validAKIs[ski].Add(op.AKI)
}
keys.skis[ski] = priv
log.Debugf("Adding key with SKI: %02x", ski)
return nil
}
示例4: DefaultSigAlgo
// DefaultSigAlgo returns an appropriate X.509 signature algorithm given
// the CA's private key.
func DefaultSigAlgo(priv crypto.Signer) x509.SignatureAlgorithm {
pub := priv.Public()
switch pub := pub.(type) {
case *rsa.PublicKey:
keySize := pub.N.BitLen()
switch {
case keySize >= 4096:
return x509.SHA512WithRSA
case keySize >= 3072:
return x509.SHA384WithRSA
case keySize >= 2048:
return x509.SHA256WithRSA
default:
return x509.SHA1WithRSA
}
case *ecdsa.PublicKey:
switch pub.Curve {
case elliptic.P256():
return x509.ECDSAWithSHA256
case elliptic.P384():
return x509.ECDSAWithSHA384
case elliptic.P521():
return x509.ECDSAWithSHA512
default:
return x509.ECDSAWithSHA1
}
default:
return x509.UnknownSignatureAlgorithm
}
}
示例5: NewSignerFromSigner
// NewSignerFromSigner takes any crypto.Signer implementation and
// returns a corresponding Signer interface. This can be used, for
// example, with keys kept in hardware modules.
func NewSignerFromSigner(signer crypto.Signer) (Signer, error) {
pubKey, err := NewPublicKey(signer.Public())
if err != nil {
return nil, err
}
return &wrappedSigner{signer, pubKey}, nil
}
示例6: generateCertificate
func generateCertificate(t *testing.T, signer crypto.Signer, out io.Writer) {
derBytes, err := x509.CreateCertificate(rand.Reader, &certTemplate, &certTemplate, signer.Public(), signer)
if err != nil {
t.Fatal("Unable to generate a certificate", err.Error())
}
if err = pem.Encode(out, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
t.Fatal("Unable to write cert to file", err.Error())
}
}
示例7: GetSubjKeyID
// GetSubjKeyID returns the subject key ID, e.g. the SHA1 sum
// of the marshaled public key
func GetSubjKeyID(privateKey crypto.Signer) ([]byte, error) {
if privateKey == nil {
return nil, InternalError{"passed-in private key is nil"}
}
marshaledKey, err := x509.MarshalPKIXPublicKey(privateKey.Public())
if err != nil {
return nil, InternalError{fmt.Sprintf("error marshalling public key: %s", err)}
}
subjKeyID := sha1.Sum(marshaledKey)
return subjKeyID[:], nil
}
示例8: jwsHasher
// jwsHasher indicates suitable JWS algorithm name and a hash function
// to use for signing a digest with the provided key.
// It returns ("", 0) if the key is not supported.
func jwsHasher(key crypto.Signer) (string, crypto.Hash) {
switch key := key.(type) {
case *rsa.PrivateKey:
return "RS256", crypto.SHA256
case *ecdsa.PrivateKey:
switch key.Params().Name {
case "P-256":
return "ES256", crypto.SHA256
case "P-384":
return "ES384", crypto.SHA384
case "P-512":
return "ES512", crypto.SHA512
}
}
return "", 0
}
示例9: SignerAlgo
// SignerAlgo returns an X.509 signature algorithm corresponding to
// the crypto.Hash provided from a crypto.Signer.
func SignerAlgo(priv crypto.Signer, h crypto.Hash) x509.SignatureAlgorithm {
switch priv.Public().(type) {
case *rsa.PublicKey:
switch h {
case crypto.SHA512:
return x509.SHA512WithRSA
case crypto.SHA384:
return x509.SHA384WithRSA
case crypto.SHA256:
return x509.SHA256WithRSA
default:
return x509.SHA1WithRSA
}
case *ecdsa.PublicKey:
switch h {
case crypto.SHA512:
return x509.ECDSAWithSHA512
case crypto.SHA384:
return x509.ECDSAWithSHA384
case crypto.SHA256:
return x509.ECDSAWithSHA256
default:
return x509.ECDSAWithSHA1
}
default:
return x509.UnknownSignatureAlgorithm
}
}
示例10: NewSignTests
// NewSignTests generates a map of test name to TestFunc that performs an opaque sign and verify.
func NewSignTests(priv crypto.Signer) map[string]testapi.TestFunc {
tests := make(map[string]testapi.TestFunc)
ptxt := []byte("Test Plaintext")
r := rand.Reader
hashes := map[string]crypto.Hash{
"sign.md5sha1": crypto.MD5SHA1,
"sign.sha1": crypto.SHA1,
"sign.sha224": crypto.SHA224,
"sign.sha256": crypto.SHA256,
"sign.sha384": crypto.SHA384,
"sign.sha512": crypto.SHA512,
}
for hashName, h := range hashes {
var msg []byte
if h == crypto.MD5SHA1 {
msg = append(hashPtxt(crypto.MD5, ptxt), hashPtxt(crypto.SHA1, ptxt)...)
} else {
msg = hashPtxt(h, ptxt)
}
tests[hashName] = func(h crypto.Hash) testapi.TestFunc {
return func() error {
sig, err := priv.Sign(r, msg, h)
if err != nil {
return err
}
switch pub := priv.Public().(type) {
case *rsa.PublicKey:
return rsa.VerifyPKCS1v15(pub, h, msg, sig)
case *ecdsa.PublicKey:
ecdsaSig := new(struct{ R, S *big.Int })
asn1.Unmarshal(sig, ecdsaSig)
if !ecdsa.Verify(pub, msg, ecdsaSig.R, ecdsaSig.S) {
return errors.New("ecdsa verify failed")
}
default:
return errors.New("unknown public key type")
}
return nil
}
}(h)
}
return tests
}
示例11: NewFromSigner
// NewFromSigner creates a new root certificate from a crypto.Signer.
func NewFromSigner(req *csr.CertificateRequest, priv crypto.Signer) (cert, csrPEM []byte, err error) {
if req.CA != nil {
if req.CA.Expiry != "" {
CAPolicy.Default.ExpiryString = req.CA.Expiry
CAPolicy.Default.Expiry, err = time.ParseDuration(req.CA.Expiry)
if err != nil {
return nil, nil, err
}
}
if req.CA.PathLength != 0 {
signer.MaxPathLen = req.CA.PathLength
}
}
var sigAlgo x509.SignatureAlgorithm
switch pub := priv.Public().(type) {
case *rsa.PublicKey:
bitLength := pub.N.BitLen()
switch {
case bitLength >= 4096:
sigAlgo = x509.SHA512WithRSA
case bitLength >= 3072:
sigAlgo = x509.SHA384WithRSA
case bitLength >= 2048:
sigAlgo = x509.SHA256WithRSA
default:
sigAlgo = x509.SHA1WithRSA
}
case *ecdsa.PublicKey:
switch pub.Curve {
case elliptic.P521():
sigAlgo = x509.ECDSAWithSHA512
case elliptic.P384():
sigAlgo = x509.ECDSAWithSHA384
case elliptic.P256():
sigAlgo = x509.ECDSAWithSHA256
default:
sigAlgo = x509.ECDSAWithSHA1
}
default:
sigAlgo = x509.UnknownSignatureAlgorithm
}
var tpl = x509.CertificateRequest{
Subject: req.Name(),
SignatureAlgorithm: sigAlgo,
}
for i := range req.Hosts {
if ip := net.ParseIP(req.Hosts[i]); ip != nil {
tpl.IPAddresses = append(tpl.IPAddresses, ip)
} else {
tpl.DNSNames = append(tpl.DNSNames, req.Hosts[i])
}
}
return signWithCSR(&tpl, priv)
}
示例12: tlsChallengeCert
// tlsChallengeCert creates a temporary certificate for TLS-SNI challenges
// with the given SANs and auto-generated public/private key pair.
// To create a cert with a custom key pair, specify WithKey option.
func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) {
var (
key crypto.Signer
tmpl *x509.Certificate
)
for _, o := range opt {
switch o := o.(type) {
case *certOptKey:
if key != nil {
return tls.Certificate{}, errors.New("acme: duplicate key option")
}
key = o.key
case *certOptTemplate:
var t = *(*x509.Certificate)(o) // shallow copy is ok
tmpl = &t
default:
// package's fault, if we let this happen:
panic(fmt.Sprintf("unsupported option type %T", o))
}
}
if key == nil {
var err error
if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil {
return tls.Certificate{}, err
}
}
if tmpl == nil {
tmpl = &x509.Certificate{
SerialNumber: big.NewInt(1),
NotBefore: time.Now(),
NotAfter: time.Now().Add(24 * time.Hour),
BasicConstraintsValid: true,
KeyUsage: x509.KeyUsageKeyEncipherment,
}
}
tmpl.DNSNames = san
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
if err != nil {
return tls.Certificate{}, err
}
return tls.Certificate{
Certificate: [][]byte{der},
PrivateKey: key,
}, nil
}
示例13: RegisterKey
// RegisterKey adds a new key to the server's internal repertoire.
func (s *Server) RegisterKey(key crypto.Signer) error {
ski, err := gokeyless.GetSKI(key.Public())
if err != nil {
return err
}
s.Lock()
defer s.Unlock()
if digest, ok := gokeyless.GetDigest(key.Public()); ok {
s.digests[digest] = ski
}
s.keys[ski] = key
s.Log.Printf("Registering key with SKI: %X", ski)
return nil
}
示例14: generateCertificate
func generateCertificate(signer crypto.Signer, gun string, startTime, endTime time.Time) (*x509.Certificate, error) {
template, err := trustmanager.NewCertificate(gun, startTime, endTime)
if err != nil {
return nil, fmt.Errorf("failed to create the certificate template for: %s (%v)", gun, err)
}
derBytes, err := x509.CreateCertificate(rand.Reader, template, template, signer.Public(), signer)
if err != nil {
return nil, fmt.Errorf("failed to create the certificate for: %s (%v)", gun, err)
}
cert, err := x509.ParseCertificate(derBytes)
if err != nil {
return nil, fmt.Errorf("failed to parse the certificate for key: %s (%v)", gun, err)
}
return cert, nil
}
示例15: NewBlock
func NewBlock(old *Block, prf PoS, ts []Transaction, signer crypto.Signer) *Block {
oldH, err := old.Hash.MarshalBinary()
if err != nil {
panic(err)
}
prevHash := sha3.Sum256(oldH)
h := Hash{
Hash: prevHash[:],
Proof: prf,
}
var tsBytes []byte
for i := range ts {
b, err := ts[i].MarshalBinary()
if err != nil {
panic(err)
}
tsBytes = append(tsBytes, b...)
}
sigBytes := util.Concat([][]byte{old.Sig.Tsig, old.Sig.Ssig})
tsig, err := signer.Sign(rand.Reader, tsBytes, crypto.SHA3_256)
if err != nil {
panic(err)
}
ssig, err := signer.Sign(rand.Reader, sigBytes, crypto.SHA3_256)
if err != nil {
panic(err)
}
sig := Signature{
Tsig: tsig,
Ssig: ssig,
}
b := Block{
Id: old.Id + 1,
Hash: h,
Trans: ts,
Sig: sig,
}
return &b
}