// Sign generates a sign based on the Algorithm instance variable. // This fulfills the `Signer` interface func (s RsaSign) PayloadSign(payload []byte) ([]byte, error) { hash, err := rsaHashForAlg(s.SignatureAlgorithm()) if err != nil { return nil, ErrUnsupportedAlgorithm } privkey := s.PrivateKey if privkey == nil { return nil, ErrMissingPrivateKey } h := hash.New() h.Write(payload) switch s.SignatureAlgorithm() { case jwa.RS256, jwa.RS384, jwa.RS512: return rsa.SignPKCS1v15(rand.Reader, privkey, hash, h.Sum(nil)) case jwa.PS256, jwa.PS384, jwa.PS512: return rsa.SignPSS(rand.Reader, privkey, hash, h.Sum(nil), &rsa.PSSOptions{ SaltLength: rsa.PSSSaltLengthAuto, }) default: return nil, ErrUnsupportedAlgorithm } }
// Signs a digest using this Identity func (this *SecretIdentity) Sign(digest *Digest) (sig *Signature) { sigout, err := rsa.SignPKCS1v15(rand.Reader, this.key, crypto.SHA224, digest.impl) if err != nil { panic(err) } return &Signature{impl: sigout} }
// Sign signs a message with a private key. The hash, h, must contain // the hash of the message to be signed and will be mutated by this function. // On success, the signature is stored in sig. Call Serialize to write it out. // If config is nil, sensible defaults will be used. func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err error) { sig.outSubpackets = sig.buildSubpackets() digest, err := sig.signPrepareHash(h) if err != nil { return } switch priv.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: sig.RSASignature.bytes, err = rsa.SignPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), sig.Hash, digest) sig.RSASignature.bitLength = uint16(8 * len(sig.RSASignature.bytes)) case PubKeyAlgoDSA: dsaPriv := priv.PrivateKey.(*dsa.PrivateKey) // Need to truncate hashBytes to match FIPS 186-3 section 4.6. subgroupSize := (dsaPriv.Q.BitLen() + 7) / 8 if len(digest) > subgroupSize { digest = digest[:subgroupSize] } r, s, err := dsa.Sign(config.Random(), dsaPriv, digest) if err == nil { sig.DSASigR.bytes = r.Bytes() sig.DSASigR.bitLength = uint16(8 * len(sig.DSASigR.bytes)) sig.DSASigS.bytes = s.Bytes() sig.DSASigS.bitLength = uint16(8 * len(sig.DSASigS.bytes)) } default: err = errors.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo))) } return }
// Sign signs a message with a private key. The hash, h, must contain // the hash of the message to be signed and will be mutated by this function. // On success, the signature is stored in sig. Call Serialize to write it out. func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey) (err os.Error) { sig.outSubpackets = sig.buildSubpackets() digest, err := sig.signPrepareHash(h) if err != nil { return } switch priv.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: sig.RSASignature.bytes, err = rsa.SignPKCS1v15(rand.Reader, priv.PrivateKey.(*rsa.PrivateKey), sig.Hash, digest) sig.RSASignature.bitLength = uint16(8 * len(sig.RSASignature.bytes)) case PubKeyAlgoDSA: r, s, err := dsa.Sign(rand.Reader, priv.PrivateKey.(*dsa.PrivateKey), digest) if err == nil { sig.DSASigR.bytes = r.Bytes() sig.DSASigR.bitLength = uint16(8 * len(sig.DSASigR.bytes)) sig.DSASigS.bytes = s.Bytes() sig.DSASigS.bitLength = uint16(8 * len(sig.DSASigS.bytes)) } default: err = error.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo))) } return }
func (a *app) registerReq(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, ErrPost, http.StatusMethodNotAllowed) return } // attempt to decode data var data main.Transaction if err := json.NewDecoder(r.Body).Decode(&data); err != nil { http.Error(w, ErrDecode, http.StatusBadRequest) } // validate the registration type if data.Type != "register" { http.Error(w, ErrBadType, http.StatusBadRequest) } // validate the email if !validateEmail(data.Email) { http.Error(w, ErrBadEmail, http.StatusBadRequest) } // sign the transaction, with the hash of the transaction json (without signature) s, err := rsa.SignPKCS1v15(rand.Reader, a.privateKey, crypto.SHA256, []byte(r.Body)) if err != nil { http.Error(w, "Could not sign registration request", http.StatusInternalServerError) } // return the signature of the hash of the email fmt.Fprintf(w, s) }
func (r NotaryResponse) signResponse(response []byte) ([]byte, error) { hash := crypto.Hash(crypto.SHA1).New() hash.Write(response) hashed := hash.Sum(nil) return rsa.SignPKCS1v15(rand.Reader, r.privateKey, crypto.SHA1, hashed) }
// Sign returns a signature of the given data using the i'th key. func (k *keychain) Sign(i int, rand io.Reader, data []byte) (sig []byte, err error) { pk := k.keys[i] h := sha1.New() h.Write(data) hh := h.Sum(nil) return rsa.SignPKCS1v15(rand, pk, crypto.SHA1, hh) }
// appleResponse takes an Apple-Challenge header value, and constructs a response for it. // To derive the response, the IP and MAC of the connection are needed, so the local address // has to be passed in. func appleResponse(challenge string, addr net.Addr) (c64 string, err error) { // iTunes seems to not pad things. Let's fix that. p64 := base64pad(challenge) ptext, err := base64.StdEncoding.DecodeString(p64) if err != nil { return } ptext = append(ptext, GetIP(addr)...) ptext = append(ptext, GetMAC(addr)...) for len(ptext) < 0x20 { ptext = append(ptext, 0) } ctext, err := rsa.SignPKCS1v15(nil, rsaPrivKey, crypto.Hash(0), ptext) if err != nil { return } c64 = base64.StdEncoding.EncodeToString(ctext) // We should respond in kind to iTunes if len(p64) != len(challenge) { c64 = base64unpad(c64) } return }
// 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 *rsa.PrivateKey, nonce string) ([]byte, error) { jwk := jwkEncode(&key.PublicKey) 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 := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.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) }
func main() { privateKey, err := rsa.GenerateKey(rand.Reader, 2048) // 개인 키와 공개 키 생성 if err != nil { fmt.Println(err) return } publicKey := &privateKey.PublicKey // 개인 키 변수 안에 공개 키가 들어있음 message := "안녕하세요. Go 언어" hash := md5.New() // 해시 인스턴스 생성 hash.Write([]byte(message)) // 해시 인스턴스에 문자열 추가 digest := hash.Sum(nil) // 문자열의 MD5 해시 값 추출 var h1 crypto.Hash signature, err := rsa.SignPKCS1v15( // 개인 키로 서명 rand.Reader, privateKey, // 개인 키 h1, digest, // MD5 해시 값 ) var h2 crypto.Hash err = rsa.VerifyPKCS1v15( // 공개 키로 서명 검증 publicKey, // 공개 키 h2, digest, // MD5 해시 값 signature, // 서명 값 ) if err != nil { fmt.Println("검증 실패") } else { fmt.Println("검증 성공") } }
// msgN, token including DigSig; gets Ack or Error func (upc *UpaxClient) IntroAndAck() (err error) { var ( name string id, ckBytes, skBytes, salt []byte digSig []byte // over name, id, ckBytes, skBytes, salt, in order ) // Send INTRO MSG ===================================== name = upc.GetName() id = upc.GetNodeID().Value() ckBytes, err = xc.RSAPubKeyToWire(&upc.ckPriv.PublicKey) if err == nil { skBytes, err = xc.RSAPubKeyToWire(&upc.skPriv.PublicKey) if err == nil { rng := xr.NewSystemRNG(0) n := uint64(rng.Int63()) salt = make([]byte, 8) binary.LittleEndian.PutUint64(salt, n) } } if err == nil { d := sha1.New() d.Write([]byte(name)) d.Write(id) d.Write(ckBytes) d.Write(skBytes) d.Write(salt) hash := d.Sum(nil) digSig, err = rsa.SignPKCS1v15( rand.Reader, upc.skPriv, crypto.SHA1, hash) } if err == nil { token := UpaxClientMsg_Token{ Name: &name, ID: id, CommsKey: ckBytes, SigKey: skBytes, Salt: salt, DigSig: digSig, } op := UpaxClientMsg_Intro request := &UpaxClientMsg{ Op: &op, ClientInfo: &token, } // SHOULD CHECK FOR TIMEOUT err = upc.writeMsg(request) } // Process ACK ======================================== if err == nil { var response *UpaxClientMsg // SHOULD CHECK FOR TIMEOUT AND VERIFY THAT IT'S AN ACK response, err = upc.readMsg() op := response.GetOp() if op != UpaxClientMsg_Ack { err = ExpectedAck } } return }
func (s *Su3File) Sign(privkey *rsa.PrivateKey) error { var hashType crypto.Hash switch s.SignatureType { case SIGTYPE_DSA: hashType = crypto.SHA1 case SIGTYPE_ECDSA_SHA256, SIGTYPE_RSA_SHA256: hashType = crypto.SHA256 case SIGTYPE_ECDSA_SHA384, SIGTYPE_RSA_SHA384: hashType = crypto.SHA384 case SIGTYPE_ECDSA_SHA512, SIGTYPE_RSA_SHA512: hashType = crypto.SHA512 default: return fmt.Errorf("Unknown signature type.") } h := hashType.New() h.Write(s.BodyBytes()) digest := h.Sum(nil) sig, err := rsa.SignPKCS1v15(rand.Reader, privkey, 0, digest) if nil != err { return err } s.Signature = sig return nil }
// signPKCS7 does the minimal amount of work necessary to embed an RSA // signature into a PKCS#7 certificate. // // We prepare the certificate using the x509 package, read it back in // to our custom data type and then write it back out with the signature. func signPKCS7(rand io.Reader, priv *rsa.PrivateKey, msg []byte) ([]byte, error) { const serialNumber = 0x5462c4dd // arbitrary name := pkix.Name{CommonName: "gomobile"} template := &x509.Certificate{ SerialNumber: big.NewInt(serialNumber), SignatureAlgorithm: x509.SHA1WithRSA, Subject: name, } b, err := x509.CreateCertificate(rand, template, template, priv.Public(), priv) if err != nil { return nil, err } c := certificate{} if _, err := asn1.Unmarshal(b, &c); err != nil { return nil, err } h := sha1.New() h.Write(msg) hashed := h.Sum(nil) signed, err := rsa.SignPKCS1v15(rand, priv, crypto.SHA1, hashed) if err != nil { return nil, err } content := pkcs7SignedData{ ContentType: oidSignedData, Content: signedData{ Version: 1, DigestAlgorithms: []pkix.AlgorithmIdentifier{{ Algorithm: oidSHA1, Parameters: asn1.RawValue{Tag: 5}, }}, ContentInfo: contentInfo{Type: oidData}, Certificates: c, SignerInfos: []signerInfo{{ Version: 1, IssuerAndSerialNumber: issuerAndSerialNumber{ Issuer: name.ToRDNSequence(), SerialNumber: serialNumber, }, DigestAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: oidSHA1, Parameters: asn1.RawValue{Tag: 5}, }, DigestEncryptionAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: oidRSAEncryption, Parameters: asn1.RawValue{Tag: 5}, }, EncryptedDigest: signed, }}, }, } return asn1.Marshal(content) }
func main() { expires := expire(10) resource := `http://d604721fxaaqy9.cloudfront.net/horizon.jpg?large=yes&license=yes` //testing value privateKey := "./private-key.pem" // The Signature value is an RSA-SHA1 digital Signature of the following JSON policy // with the RESOURCE and EXPIRES values replaced with your values //{"Statement":[{"Resource":"RESOURCE","Condition":{"DateLessThan":{"AWS:EpochTime":EXPIRES}}}]} fmt.Printf("\nexpires would be:%s, and it's being reset to: 1258237200 for testing\n", expires) p1 := `{"Statement":[{"Resource":"` p2 := resource p3 := `","Condition":{"DateLessThan":{"AWS:EpochTime":` p4 := "1258237200" //normally use expires, but this is for testing p5 := `}}}]}` toSign := p1 + p2 + p3 + p4 + p5 fmt.Printf("We're going to sign %s, of Type %T\n", toSign, toSign) key, err := privkey(privateKey) if err != nil { fmt.Print("oops") } h := sha1.New() h.Write([]byte(toSign)) sum := h.Sum() sig, err := rsa.SignPKCS1v15(rand.Reader, key, rsa.HashSHA1, sum) if err != nil { fmt.Print("oops2") } f := bytes.NewBuffer(sig) g := f.String() fmt.Printf("The Signed String is: %s\n and is of type:%T\n", g, g) }
func makeCertificate(email string, publicKey map[string]string, durationSec int64) (signed []byte, err error) { header := []byte(`{"alg": "RS256"}`) encodedHeader := base64Encode(header) iat := (time.Now().Unix() - 600) * 1000 exp := (time.Now().Unix() + durationSec) * 1000 cert := identityCert{certIssuer, iat, exp, publicKey, principal{email}} payload, err := json.Marshal(cert) if err != nil { return nil, err } encodedPayload := base64Encode(payload) signingBase := dotJoin(encodedHeader, encodedPayload) hash := sha256.New() hash.Write(signingBase) hashed := hash.Sum(nil) signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed) if err != nil { return nil, err } encodedSignature := base64Encode(signature) return dotJoin(signingBase, encodedSignature), nil }
//SignWithRSA sign given encrypted data with RSA algorithm func SignRSA(raw []byte, algorithm crypto.Hash) []byte { if raw == nil { return nil } privateKey := []byte(PrivateKey) if !ginutil.IsProduction() { privateKey = []byte(TestPrivateKey) } block, _ := pem.Decode(privateKey) if block == nil { return nil } privInterface, err := x509.ParsePKCS8PrivateKey(block.Bytes) if err != nil { return nil } priv := privInterface.(*rsa.PrivateKey) var data []byte if algorithm == crypto.SHA1 { data = EncryptSHA(raw) } else { data = EncryptMD5(EncryptSHA(raw)) } signed, err := rsa.SignPKCS1v15(rand.Reader, priv, algorithm, data) if err != nil { return nil } return signed }
// Generates a signature of a JSON-marshalable "message" object, using the given RSA private key. // If includeDate is true, a timestamp will be added to the signature; if expiration is also // nonzero, it will be included as the expiration interval, i.e. how long the signature remains // valid after being signed. // // Making any changes to the message object will invalidate the signature, unless the changes are // in ignored keys. Any underscore-prefixed key (except "_id") is ignored, as is "(signed)". func CreateSignature(message map[string]interface{}, key *rsa.PrivateKey, includeDate bool, expiration time.Duration) (*Signature, error) { signature := Signature{ PublicKey: key.PublicKey, messageDigest: canonicalDigest(message), } if includeDate { now := time.Now() signature.Date = &now if expiration > 0 { expires := now.Add(expiration) signature.Expiration = &expires } } sigJson, err := json.Marshal(&signature) if err != nil { return nil, err } digest := sha1.Sum(sigJson) signature.signatureBytes, err = rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA1, digest[:]) if err != nil { return nil, err } return &signature, nil }
/** * Set a timestamp and calculate a digital signature. First * calculate the SHA1 hash of the pubKey, title, timestamp, * and content lines, excluding the terminating CRLF in each * case, then encrypt that using the RSA private key supplied. * * @param key RSAKey whose secret materials are used to sign */ func (sl *SignedBList) Sign(skPriv *rsa.PrivateKey) (err error) { var ( digSig, hash []byte ) if sl.DigSig != nil { err = ListAlreadySigned } else if skPriv == nil { err = NilPrivateKey } else { sl.Timestamp = xu.Timestamp(time.Now().UnixNano()) hash, err = sl.HashBody() if err == nil { digSig, err = rsa.SignPKCS1v15( rand.Reader, skPriv, crypto.SHA1, hash) if err == nil { sl.DigSig = digSig } } if err != nil { sl.Timestamp = 0 // restore to default } } return }
// WriteAuthenticatedDataPackage creates an AuthenticatedDataPackage // containing the specified data and signed by the given key. The output // conforms with the legacy format here: // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/c25d080f6827b141fe637050ce0d5bd0ae2e9db5/Automation/psi_ops_crypto_tools.py func WriteAuthenticatedDataPackage( data string, signingPublicKey, signingPrivateKey string) ([]byte, error) { derEncodedPrivateKey, err := base64.StdEncoding.DecodeString(signingPrivateKey) if err != nil { return nil, ContextError(err) } rsaPrivateKey, err := x509.ParsePKCS1PrivateKey(derEncodedPrivateKey) if err != nil { return nil, ContextError(err) } signature, err := rsa.SignPKCS1v15( rand.Reader, rsaPrivateKey, crypto.SHA256, sha256sum(data)) if err != nil { return nil, ContextError(err) } packageJSON, err := json.Marshal( &AuthenticatedDataPackage{ Data: data, SigningPublicKeyDigest: sha256sum(signingPublicKey), Signature: signature, }) if err != nil { return nil, ContextError(err) } return packageJSON, nil }
// Encode encodes a signed JWS with provided header and claim set. func Encode(header *Header, c *ClaimSet, signature []byte) (payload string, err error) { var encodedHeader, encodedClaimSet string encodedHeader, err = header.encode() if err != nil { return } encodedClaimSet, err = c.encode() if err != nil { return } ss := fmt.Sprintf("%s.%s", encodedHeader, encodedClaimSet) parsed, err := parsePrivateKey(signature) if err != nil { return } h := sha256.New() h.Write([]byte(ss)) b, err := rsa.SignPKCS1v15(rand.Reader, parsed, crypto.SHA256, h.Sum(nil)) if err != nil { return } sig := base64Encode(b) return fmt.Sprintf("%s.%s", ss, sig), nil }
func (k *keychain) Sign(i int, rand io.Reader, data []byte) (sig []byte, err error) { hashFunc := crypto.SHA1 h := hashFunc.New() h.Write(data) digest := h.Sum(nil) return rsa.SignPKCS1v15(rand, k.key, hashFunc, digest) }
// Sign the given hex-endcoded hash checksum and return a Signature // @@TODO Remove this -- undeeded func (pk PrivateKey) SignSHA256(hexbytes []byte) (Signature, error) { if hex.DecodedLen(len(hexbytes)) != sha256.Size { return nil, ErrPrivateKeySHA256 } // Decode hex bytes into raw bytes decodedBytes := make([]byte, hex.DecodedLen(len(hexbytes))) _, err := hex.Decode(decodedBytes, hexbytes) if err != nil { return nil, errors.Wrap(err, ErrPrivateKeySHA256) } // Get the rsa cryptokey for signing cryptoKey, err := pk.GetCryptoKey() if err != nil { return nil, errors.Wrap(err, ErrPrivatKeySign) } // Compute the signature and return the results rawSignature, err := rsa.SignPKCS1v15(rand.Reader, cryptoKey, crypto.SHA256, decodedBytes) if err != nil { return nil, errors.Wrap(err, ErrPrivatKeySign) } return Signature(rawSignature), nil }
// sign computes the signature for a Token. The details for this can be found // in the OAuth2 Service Account documentation. // https://developers.google.com/accounts/docs/OAuth2ServiceAccount#computingsignature func (t *Token) sign() error { if t.useExternalSigner { fulldata, sig, err := t.signer.Sign(t) if err != nil { return err } split := strings.Split(string(fulldata), ".") if len(split) != 2 { return errors.New("no token returned") } t.header = split[0] t.claim = split[1] t.sig = base64Encode(sig) return err } ss := fmt.Sprintf("%s.%s", t.header, t.claim) if t.pKey == nil { err := t.parsePrivateKey() if err != nil { return err } } h := sha256.New() h.Write([]byte(ss)) b, err := rsa.SignPKCS1v15(rand.Reader, t.pKey, crypto.SHA256, h.Sum(nil)) t.sig = base64Encode(b) return err }
// CreateCRL returns a DER encoded CRL, signed by this Certificate, that // contains the given list of revoked certificates. func (c *Certificate) CreateCRL(rand io.Reader, priv *rsa.PrivateKey, revokedCerts []pkix.RevokedCertificate, now, expiry *time.Time) (crlBytes []byte, err os.Error) { tbsCertList := pkix.TBSCertificateList{ Version: 2, Signature: pkix.AlgorithmIdentifier{ Algorithm: oidSignatureSHA1WithRSA, }, Issuer: c.Subject.ToRDNSequence(), ThisUpdate: now, NextUpdate: expiry, RevokedCertificates: revokedCerts, } tbsCertListContents, err := asn1.Marshal(tbsCertList) if err != nil { return } h := sha1.New() h.Write(tbsCertListContents) digest := h.Sum() signature, err := rsa.SignPKCS1v15(rand, priv, crypto.SHA1, digest) if err != nil { return } return asn1.Marshal(pkix.CertificateList{ TBSCertList: tbsCertList, SignatureAlgorithm: pkix.AlgorithmIdentifier{ Algorithm: oidSignatureSHA1WithRSA, }, SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, }) }
func RsaOpensslSign(pub *rsa.PrivateKey, h crypto.Hash, msg []byte) (s []byte, err error) { h1 := h.New() h1.Write(msg) digest := h1.Sum(nil) s, err = rsa.SignPKCS1v15(nil, pub, h, digest) return }
func signManifest(manifest Manifest, privKey *rsa.PrivateKey) ([]byte, error) { // marshal the manifest (without the signature field set) manifestToSign, err := json.Marshal(manifest) if err != nil { return nil, err } // calculate the Sha1 of the manifest bytes var h crypto.Hash manifestSha1 := sha1.New() manifestSha1.Write(manifestToSign) manShaVal := manifestSha1.Sum(nil) // calculate the signature of the manifest sig, err := rsa.SignPKCS1v15(rand.Reader, privKey, h, manShaVal) if err != nil { return nil, err } // set the Signature field of the manifest manifest.Signature = sig // marshal the manifest with signature return json.Marshal(manifest) }
// Implements the Sign method from SigningMethod // For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA private key as // []byte, or an rsa.PrivateKey structure. func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { var err error var rsaKey *rsa.PrivateKey switch k := key.(type) { case []byte: if rsaKey, err = ParseRSAPrivateKeyFromPEM(k); err != nil { return "", err } case *rsa.PrivateKey: rsaKey = k default: return "", ErrInvalidKey } // Create the hasher if !m.Hash.Available() { return "", ErrHashUnavailable } hasher := m.Hash.New() hasher.Write([]byte(signingString)) // Sign the string and return the encoded bytes if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { return EncodeSegment(sigBytes), nil } else { return "", err } }
func main() { privateKey, err := rsa.GenerateKey(rand.Reader, 1024) if err != nil { fmt.Printf("rsa.GenerateKey: %v\n", err) return } message := "Hello World!" messageBytes := bytes.NewBufferString(message) hash := sha512.New() hash.Write(messageBytes.Bytes()) digest := hash.Sum(nil) fmt.Printf("messageBytes: %v\n", messageBytes) fmt.Printf("hash: %V\n", hash) fmt.Printf("digest: %v\n", digest) signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA512, digest) if err != nil { fmt.Printf("rsa.SignPKCS1v15 error: %v\n", err) return } fmt.Printf("signature: %v\n", signature) err = rsa.VerifyPKCS1v15(&privateKey.PublicKey, crypto.SHA512, digest, signature) if err != nil { fmt.Printf("rsa.VerifyPKCS1v15 error: %V\n", err) } fmt.Println("Signature good!") }
// CreateSignature builds a signature over the given data using the specified hash algorithm and private key. func CreateSignature(privKey crypto.PrivateKey, hashAlgo HashAlgorithm, data []byte) (DigitallySigned, error) { var sig DigitallySigned sig.Algorithm.Hash = hashAlgo hash, hashType, err := generateHash(sig.Algorithm.Hash, data) if err != nil { return sig, err } switch privKey := privKey.(type) { case rsa.PrivateKey: sig.Algorithm.Signature = RSA sig.Signature, err = rsa.SignPKCS1v15(rand.Reader, &privKey, hashType, hash) return sig, err case ecdsa.PrivateKey: sig.Algorithm.Signature = ECDSA var ecdsaSig dsaSig ecdsaSig.R, ecdsaSig.S, err = ecdsa.Sign(rand.Reader, &privKey, hash) if err != nil { return sig, err } sig.Signature, err = asn1.Marshal(ecdsaSig) return sig, err default: return sig, fmt.Errorf("unsupported private key type %T", privKey) } }
func (auth *Auth) assertion() ([]byte, error) { header, err := json.Marshal( map[string]interface{}{ "typ": "JWT", "alg": "RS256", }) if err != nil { return nil, err } parts := [3][]byte{} parts[0] = b64urlencode(header) now := time.Now() claims, err := json.Marshal( map[string]interface{}{ "iss": auth.Email, "scope": strings.Join(auth.Scope, " "), "aud": aud, "exp": now.Add(time.Hour).Unix(), "iat": now.Unix(), }) if err != nil { return nil, err } parts[1] = b64urlencode(claims) sha := sha256.New() sha.Write(bytes.Join(parts[:2], separator)) signature, err := rsa.SignPKCS1v15(rand.Reader, auth.Key, crypto.SHA256, sha.Sum(nil)) if err != nil { return nil, err } parts[2] = b64urlencode(signature) return bytes.Join(parts[:], separator), nil }