Ejemplo n.º 1
0
// Implements the Sign method from SigningMethod
// For this signing method, key must be an rsa.PrivateKey struct
func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) {
	var rsaKey *rsa.PrivateKey

	switch k := key.(type) {
	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.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil {
		return EncodeSegment(sigBytes), nil
	} else {
		return "", err
	}
}
Ejemplo n.º 2
0
func (alg *RsaPssUsingSha) Sign(securedInput []byte, key interface{}) (signature []byte, err error) {
	if privKey, ok := key.(*rsa.PrivateKey); ok {
		return rsa.SignPSS(rand.Reader, privKey, hashFunc(alg.keySizeBits), sha(alg.keySizeBits, securedInput), &rsa.PSSOptions{SaltLength: alg.saltSizeBytes})
	}

	return nil, errors.New("RsaPssUsingSha.Sign(): expects key to be '*rsa.PrivateKey'")
}
Ejemplo n.º 3
0
// 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
	}
}
Ejemplo n.º 4
0
// Sign generates a digital signature of the message passed in.
func Sign(prv *rsa.PrivateKey, m []byte) (sig []byte, err error) {
	h := sha256.New()
	h.Write(m)
	d := h.Sum(nil)
	sig, err = rsa.SignPSS(rand.Reader, prv, crypto.SHA256, d, nil)
	return
}
Ejemplo n.º 5
0
func sign(prv *rsa.PrivateKey, msg string) (signature string, err error) {
	h := sha256.New()
	h.Write([]byte(msg))
	d := h.Sum(nil)
	sigBin, _ := rsa.SignPSS(rand.Reader, prv, crypto.SHA256, d, nil)
	signature = encodeBase64(sigBin)
	return
}
Ejemplo n.º 6
0
func SignMessageWithKey(key *rsa.PrivateKey, msg string) (sig []byte, err error) {
	hashFunction := sha256.New()
	io.WriteString(hashFunction, msg)
	hashSum := hashFunction.Sum(nil)

	sig, err = rsa.SignPSS(rand.Reader, key, crypto.SHA256, hashSum, nil)
	return
}
Ejemplo n.º 7
0
func BenchmarkRsaSign(b *testing.B) {
	key, _ := rsa.GenerateKey(rand.Reader, 2048)
	val := sha256.Sum256(make([]byte, 32, 32))

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		rsa.SignPSS(rand.Reader, key, crypto.SHA256, val[:], nil)
	}
}
Ejemplo n.º 8
0
func (r *rsaPSSSigner) signMessage(key crypto.PrivateKey, config *Config, msg []byte) ([]byte, error) {
	rsaKey, ok := key.(*rsa.PrivateKey)
	if !ok {
		return nil, errors.New("invalid key type for RSA-PSS")
	}

	h := r.hash.New()
	h.Write(msg)
	return rsa.SignPSS(config.rand(), rsaKey, r.hash, h.Sum(nil), &pssOptions)
}
Ejemplo n.º 9
0
// Sign uses the private key to sign provided string and returns the result as a base64.URLEncoded string
func (m *Manager) Sign(s string) (string, error) {
	h := sha256.New()
	h.Write([]byte(s))
	d := h.Sum(nil)
	sig, err := rsa.SignPSS(rand.Reader, m.PrivateKey, crypto.SHA256, d, nil)
	if err != nil {
		return "", err
	}

	return base64.URLEncoding.EncodeToString(sig), nil
}
Ejemplo n.º 10
0
// Sign implements the Sign method from SigningMethod.
// For this signing method, key must be an *rsa.PrivateKey.
func (m *SigningMethodRSAPSS) Sign(raw []byte, key interface{}) (Signature, error) {
	rsaKey, ok := key.(*rsa.PrivateKey)
	if !ok {
		return nil, ErrInvalidKey
	}
	sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, m.sum(raw), m.Options)
	if err != nil {
		return nil, err
	}
	return Signature(sigBytes), nil
}
func GenerateMessageSignature(senderPrivKey *rsa.PrivateKey, plainText []byte) ([]byte, error) {
	pssh := newhash.New()
	_, err := pssh.Write(plainText)
	if err != nil {
		return nil, err
	}

	hashed := pssh.Sum(nil)
	signature, err := rsa.SignPSS(rand.Reader, senderPrivKey, newhash, hashed, opts)
	return signature, err
}
Ejemplo n.º 12
0
// Encrypt signs the message with the private key, and encrypts it to
// the certificate supplied.
func Encrypt(priv *rsa.PrivateKey, cert *x509.Certificate, msg []byte) ([]byte, bool) {
	var pub *rsa.PublicKey
	switch certPub := cert.PublicKey.(type) {
	case *rsa.PublicKey:
		pub = certPub
	default:
		return nil, false
	}

	var signed = signature{msg, nil}

	h := sha256.New()
	h.Write(msg)

	var err error
	signed.Signature, err = rsa.SignPSS(rand.Reader, priv, crypto.SHA256,
		h.Sum(nil), nil)
	if err != nil {
		return nil, false
	}

	out, err := asn1.Marshal(signed)
	if err != nil {
		return nil, false
	}

	key := aesgcm.NewKey()
	if key == nil {
		return nil, false
	}

	out, ok := aesgcm.Encrypt(key, out)
	if !ok {
		return nil, false
	}

	var message message
	message.Signed = out

	h.Reset()
	message.Key, err = rsa.EncryptOAEP(h, rand.Reader, pub, key, nil)
	if err != nil {
		return nil, false
	}

	out, err = asn1.Marshal(message)
	if err != nil {
		return nil, false
	}

	return out, true
}
Ejemplo n.º 13
0
func main() {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	checkFatal(err)

	message := []byte("Binding contractual agreement...")

	h := sha256.New()
	h.Write(message)
	digest := h.Sum(nil)
	sig, err := rsa.SignPSS(rand.Reader, priv, crypto.SHA256, digest, nil)
	checkFatal(err)

	fmt.Printf("Signature: %x\n", sig)
	err = rsa.VerifyPSS(&priv.PublicKey, crypto.SHA256, digest, sig, nil)
	fmt.Printf("Signature OK: %v\n", err == nil)
}
Ejemplo n.º 14
0
func rsaPSSSign(privKey data.PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error) {
	if privKey, ok := privKey.(*data.RSAPrivateKey); !ok {
		return nil, fmt.Errorf("private key type not supported: %s", privKey.Algorithm())
	}

	// Create an rsa.PrivateKey out of the private key bytes
	rsaPrivKey, err := x509.ParsePKCS1PrivateKey(privKey.Private())
	if err != nil {
		return nil, err
	}

	// Use the RSA key to RSASSA-PSS sign the data
	sig, err := rsa.SignPSS(rand.Reader, rsaPrivKey, hash, hashed[:], &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
	if err != nil {
		return nil, err
	}

	return sig, nil
}
Ejemplo n.º 15
0
// Sign the given payload
func (ctx rsaDecrypterSigner) signPayload(payload []byte, alg SignatureAlgorithm) (Signature, error) {
	var hash crypto.Hash

	switch alg {
	case RS256, PS256:
		hash = crypto.SHA256
	case RS384, PS384:
		hash = crypto.SHA384
	case RS512, PS512:
		hash = crypto.SHA512
	default:
		return Signature{}, ErrUnsupportedAlgorithm
	}

	hasher := hash.New()

	// According to documentation, Write() on hash never fails
	_, _ = hasher.Write(payload)
	hashed := hasher.Sum(nil)

	var out []byte
	var err error

	switch alg {
	case RS256, RS384, RS512:
		out, err = rsa.SignPKCS1v15(randReader, ctx.privateKey, hash, hashed)
	case PS256, PS384, PS512:
		out, err = rsa.SignPSS(randReader, ctx.privateKey, hash, hashed, &rsa.PSSOptions{
			SaltLength: rsa.PSSSaltLengthAuto,
		})
	}

	if err != nil {
		return Signature{}, err
	}

	return Signature{
		Signature: out,
		protected: &rawHeader{},
	}, nil
}
Ejemplo n.º 16
0
func rsaSign(privKey data.PrivateKey, message []byte) ([]byte, error) {
	if privKey.Algorithm() != data.RSAKey {
		return nil, fmt.Errorf("private key type not supported: %s", privKey.Algorithm())
	}

	hashed := sha256.Sum256(message)

	// Create an rsa.PrivateKey out of the private key bytes
	rsaPrivKey, err := x509.ParsePKCS1PrivateKey(privKey.Private())
	if err != nil {
		return nil, err
	}

	// Use the RSA key to RSASSA-PSS sign the data
	sig, err := rsa.SignPSS(rand.Reader, rsaPrivKey, crypto.SHA256, hashed[:], &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
	if err != nil {
		return nil, err
	}

	return sig, nil
}
Ejemplo n.º 17
0
func NewMsg(from, to string, fromkey *rsa.PrivateKey, tokey *rsa.PublicKey, data []byte) (*Msg, error) {
	hash := crypto.SHA256
	max := tokey.N.BitLen()/8 - 2*hash.Size() - 2
	num := len(data) / max
	if len(data)%max > 0 {
		num++
	}
	msg := &Msg{
		From:      from,
		To:        to,
		Data:      make([][]byte, num),
		Signature: make([][]byte, num),
	}
	j := 0
	for i := 0; i < len(data); i += max {
		end := i + max
		if end > len(data) {
			end = len(data)
		}

		ciphertex, err := rsa.EncryptOAEP(hash.New(), rand.Reader, tokey, data[i:end], []byte(""))
		if err != nil {
			return nil, e.Push(err, "can't encrypt message")
		}
		pssh := hash.New()
		pssh.Write(data[i:end])
		hashed := pssh.Sum(nil)
		var opts rsa.PSSOptions
		opts.SaltLength = rsa.PSSSaltLengthAuto
		signature, err := rsa.SignPSS(rand.Reader, fromkey, hash, hashed, &opts)
		if err != nil {
			return nil, e.Push(err, "can't sign the message")
		}
		msg.Data[j] = ciphertex
		msg.Signature[j] = signature
		j++
	}

	return msg, nil
}
Ejemplo n.º 18
0
func SignMessage(pmsg PeerMessage) PeerMessage {

	pmsg_bytes, err := json.Marshal(pmsg)
	if err != nil {
		log.Fatal("(SignMessage) JSON Error: ", err)
	}

	newhash := crypto.SHA1
	pssh := newhash.New()
	pssh.Write(pmsg_bytes)
	hashed := pssh.Sum(nil)

	signaturePSS, err := rsa.SignPSS(rand.Reader, pvkey, newhash, hashed, nil)
	if err != nil {
		log.Fatal(err)
	}

	pmsg.Hashed = hashed
	pmsg.Sig = signaturePSS

	return pmsg
}
Ejemplo n.º 19
0
//Sign creates the signature for a message
func (rsaKey *RsaKey) Sign(message string) (signature string, err error) {
	var signatureBytes []byte
	hashAlgorithm := crypto.SHA256

	messageBytes := bytes.NewBufferString(message)

	//hash
	hasher := hashAlgorithm.New()
	hasher.Write(messageBytes.Bytes())
	messageHash := hasher.Sum(nil)

	//sign
	var pssOptions rsa.PSSOptions
	pssOptions.SaltLength = saltSize
	pssOptions.Hash = hashAlgorithm
	signatureBytes, err = rsa.SignPSS(rand.Reader, rsaKey.privateKey, hashAlgorithm, messageHash, &pssOptions)
	if err != nil {
		return
	}
	signature = base64.StdEncoding.EncodeToString(signatureBytes)

	return
}
Ejemplo n.º 20
0
func SignBytes(data []byte, priv *rsa.PrivateKey) (s []byte, err error) {

	hash := sha256.Sum256(data)
	return rsa.SignPSS(rand.Reader, priv, crypto.SHA256, hash[:], &rsa.PSSOptions{})
}
Ejemplo n.º 21
0
Archivo: rsa.go Proyecto: knq/jwt
func (r rsaMethod) Verify(pub *rsa.PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error {
	return r.verifyFunc(pub, hash, hashed, sig)
}

// rsaMethodPKCS1v15 provides a RSA method that signs and verifies with
// PKCS1v15.
var rsaMethodPKCS1v15 = rsaMethod{
	signFunc:   rsa.SignPKCS1v15,
	verifyFunc: rsa.VerifyPKCS1v15,
}

// rsaMethodPSS provides a RSA method that signs and verifies with PSS.
var rsaMethodPSS = rsaMethod{
	signFunc: func(rand io.Reader, priv *rsa.PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error) {
		return rsa.SignPSS(rand, priv, hash, hashed, &rsa.PSSOptions{
			SaltLength: rsa.PSSSaltLengthAuto,
			Hash:       hash,
		})
	},
	verifyFunc: func(pub *rsa.PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error {
		return rsa.VerifyPSS(pub, hash, hashed, sig, &rsa.PSSOptions{
			SaltLength: rsa.PSSSaltLengthAuto,
			Hash:       hash,
		})
	},
}

// rsaSigner provides a RSA Signer.
type rsaSigner struct {
	alg    Algorithm
	method RSASignerVerifier
	hash   crypto.Hash
Ejemplo n.º 22
0
func main() {

	// Generate RSA Keys
	miryanPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)

	if err != nil {
		fmt.Println(err.Error)
		os.Exit(1)
	}

	miryanPublicKey := &miryanPrivateKey.PublicKey

	raulPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)

	if err != nil {
		fmt.Println(err.Error)
		os.Exit(1)
	}

	raulPublicKey := &raulPrivateKey.PublicKey

	fmt.Println("Private Key : ", miryanPrivateKey)
	fmt.Println("Public key ", miryanPublicKey)
	fmt.Println("Private Key : ", raulPrivateKey)
	fmt.Println("Public key ", raulPublicKey)

	//Encrypt Miryan Message
	message := []byte("the code must be like a piece of music")
	label := []byte("")
	hash := sha256.New()

	ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, raulPublicKey, message, label)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Printf("OAEP encrypted [%s] to \n[%x]\n", string(message), ciphertext)
	fmt.Println()

	// Message - Signature
	var opts rsa.PSSOptions
	opts.SaltLength = rsa.PSSSaltLengthAuto // for simple example
	PSSmessage := message
	newhash := crypto.SHA256
	pssh := newhash.New()
	pssh.Write(PSSmessage)
	hashed := pssh.Sum(nil)

	signature, err := rsa.SignPSS(rand.Reader, miryanPrivateKey, newhash, hashed, &opts)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Printf("PSS Signature : %x\n", signature)

	// Decrypt Message
	plainText, err := rsa.DecryptOAEP(hash, rand.Reader, raulPrivateKey, ciphertext, label)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Printf("OAEP decrypted [%x] to \n[%s]\n", ciphertext, plainText)

	//Verify Signature
	err = rsa.VerifyPSS(miryanPublicKey, newhash, hashed, signature, &opts)

	if err != nil {
		fmt.Println("Who are U? Verify Signature failed")
		os.Exit(1)
	} else {
		fmt.Println("Verify Signature successful")
	}

}