Exemple #1
1
// Verify the given payload
func (ctx rsaEncrypterVerifier) verifyPayload(payload []byte, signature []byte, alg SignatureAlgorithm) 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 ErrUnsupportedAlgorithm
	}

	hasher := hash.New()

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

	switch alg {
	case RS256, RS384, RS512:
		return rsa.VerifyPKCS1v15(ctx.publicKey, hash, hashed, signature)
	case PS256, PS384, PS512:
		return rsa.VerifyPSS(ctx.publicKey, hash, hashed, signature, nil)
	}

	return ErrUnsupportedAlgorithm
}
Exemple #2
0
// Implements the Verify method from SigningMethod
// For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA public key as
// []byte, or an rsa.PublicKey structure.
func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
	var err error

	// Decode the signature
	var sig []byte
	fmt.Println("right: ")
	if sig, err = DecodeSegment(signature); err != nil {
		return err
	}

	var rsaKey *rsa.PublicKey

	switch k := key.(type) {
	case []byte:
		if rsaKey, err = ParseRSAPublicKeyFromPEM(k); err != nil {
			return err
		}
	case *rsa.PublicKey:
		rsaKey = k
	default:
		return ErrInvalidKey
	}

	// Create hasher
	if !m.Hash.Available() {
		return ErrHashUnavailable
	}
	hasher := m.Hash.New()
	hasher.Write([]byte(signingString))

	// Verify the signature
	err = rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
	fmt.Printf("%#v\n, %#v\n, %#v\n, %#v\n, %#v\n", rsaKey, m.Hash, hasher.Sum(nil), sig, err)
	return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
}
func verifyRSASignature(key *rsa.PublicKey, hash crypto.Hash, signatureBytes []byte, digest []byte) error {
	err := rsa.VerifyPKCS1v15(key, hash, digest, signatureBytes)
	if err != nil {
		return errors.New("certificatetransparency: signature verification failed: " + err.Error())
	}
	return nil
}
Exemple #4
0
// Implements the Verify method from SigningMethod
// For this signing method, must be an rsa.PublicKey structure.
func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
	var err error

	// Decode the signature
	var sig []byte
	if sig, err = DecodeSegment(signature); err != nil {
		return err
	}

	var rsaKey *rsa.PublicKey
	var ok bool

	if rsaKey, ok = key.(*rsa.PublicKey); !ok {
		return ErrInvalidKeyType
	}

	// Create hasher
	if !m.Hash.Available() {
		return ErrHashUnavailable
	}
	hasher := m.Hash.New()
	hasher.Write([]byte(signingString))

	// Verify the signature
	return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
}
Exemple #5
0
// Returns error on failure, nil on success
// Updates a public key, signed by the user
// signature should be signed on JSON-marshalled transaction data
func UpdatePublicKey(key rsa.PublicKey, sig []byte, email string) error {
	// value already in map, don't reregister
	oldKey, ok := Database[email]
	if !ok {
		return fmt.Errorf("You have never registered for a public key")
	}
	jsonBytes, err := json.Marshal(&Transaction{Type: Update, Email: email, PublicKey: key})
	if err != nil {
		return err
	}

	// protocol: user uses SHA256 to hash the transaction
	hash := sha256.Sum256(jsonBytes)
	hashbytes := hash[:]
	if err := rsa.VerifyPKCS1v15(&oldKey, crypto.SHA256, hashbytes, sig); err != nil {
		return fmt.Errorf("bad signature")
	}
	trans := Transaction{
		Type:      Update,
		Email:     email,
		PublicKey: key,
		Signature: sig,
	}
	// add this to our "block" that we're working on
	addToBlock(trans)
	return nil
}
Exemple #6
0
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("검증 성공")
	}
}
Exemple #7
0
// QuoteVerify verifies that a quote was genuinely provided by the TPM. It
// takes the quote data, quote validation blob, public half of the AIK,
// current PCR values and the nonce used in the original quote request. It
// then verifies that the validation block is a valid signature for the
// quote data, that the secrets are the same (in order to avoid replay
// attacks), and that the PCR values are the same. It returns an error if
// any stage of the validation fails.
func QuoteVerify(data []byte, validation []byte, aikpub []byte, pcrvalues [][]byte, secret []byte) error {
	n := big.NewInt(0)
	n.SetBytes(aikpub)
	e := 65537

	pKey := rsa.PublicKey{N: n, E: int(e)}

	dataHash := sha1.Sum(data[:])

	err := rsa.VerifyPKCS1v15(&pKey, crypto.SHA1, dataHash[:], validation)
	if err != nil {
		return err
	}

	pcrHash := data[8:28]
	nonceHash := data[28:48]

	secretHash := sha1.Sum(secret[:])

	if bytes.Equal(secretHash[:], nonceHash) == false {
		return fmt.Errorf("Secret doesn't match")
	}

	pcrComposite := []byte{0x00, 0x02, 0xff, 0xff, 0x00, 0x00, 0x01, 0x40}
	for i := 0; i < 16; i++ {
		pcrComposite = append(pcrComposite, pcrvalues[i]...)
	}
	pcrCompositeHash := sha1.Sum(pcrComposite[:])

	if bytes.Equal(pcrCompositeHash[:], pcrHash) == false {
		return fmt.Errorf("PCR values don't match")
	}

	return nil
}
Exemple #8
0
// VerifySignature returns nil iff sig is a valid signature, made by this
// public key, of the data hashed into signed. signed is mutated by this call.
func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err os.Error) {
	if !pk.CanSign() {
		return error.InvalidArgumentError("public key cannot generate signatures")
	}

	signed.Write(sig.HashSuffix)
	hashBytes := signed.Sum()

	if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
		return error.SignatureError("hash tag doesn't match")
	}

	if pk.PubKeyAlgo != sig.PubKeyAlgo {
		return error.InvalidArgumentError("public key and signature use different algorithms")
	}

	switch pk.PubKeyAlgo {
	case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
		rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey)
		err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature)
		if err != nil {
			return error.SignatureError("RSA verification failure")
		}
		return nil
	case PubKeyAlgoDSA:
		dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey)
		if !dsa.Verify(dsaPublicKey, hashBytes, sig.DSASigR, sig.DSASigS) {
			return error.SignatureError("DSA verification failure")
		}
		return nil
	default:
		panic("shouldn't happen")
	}
	panic("unreachable")
}
Exemple #9
0
Fichier : rs.go Projet : benjic/jwt
func (v RSValidator) validate(jwt *jwt) (bool, error) {

	if v.PublicKey == nil {
		return false, ErrBadSignature
	}

	jwt.Header.Algorithm = v.algorithm
	jwt.rawEncode()

	signature, err := base64.URLEncoding.DecodeString(string(jwt.Signature))

	if err != nil {
		return false, err
	}

	hsh := v.hashType.New()
	hsh.Write([]byte(string(jwt.headerRaw) + "." + string(jwt.payloadRaw)))
	hash := hsh.Sum(nil)

	err = rsa.VerifyPKCS1v15(v.PublicKey, v.hashType, hash, signature)

	if err != nil {
		return false, ErrBadSignature
	}

	return true, nil
}
//VerifySignature verify whether the given signature is correct
func VerifySignature(raw []byte, signature string, algorithm crypto.Hash) bool {
	if raw == nil || signature == "" {
		return false
	}
	publicKey := []byte(PublicKey)
	if !ginutil.IsProduction() {
		publicKey = []byte(TestPublicKey)
	}
	block, _ := pem.Decode(publicKey)
	if block == nil {
		return false
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return false
	}
	pub := pubInterface.(*rsa.PublicKey)
	var data []byte
	if algorithm == crypto.SHA1 {
		data = EncryptSHA(raw)
	} else {
		data = EncryptMD5(EncryptSHA(raw))
	}
	err = rsa.VerifyPKCS1v15(pub, algorithm, data, DecryptBase64(signature))
	if err != nil {
		return false
	}
	return true
}
Exemple #11
0
func TestEscrowServer(t *testing.T) {

	k1, k2, err := octokey.GeneratePartialKey()

	if err != nil {
		t.Fatal(err)
	}

	_, err = uploadFile("http://localhost:5005/upload", "key", []byte(k2.String()))
	if err != nil {
		t.Fatal(err)
	}

	p2 := &octokey.PartialSigner{"http://localhost:5005/sign", (*octokey.PublicKey)(&k2.PublicKey)}

	s := new(mrsa.Session)
	s.Decryptors = append(s.Decryptors, p2)
	s.Decryptors = append(s.Decryptors, k1)
	s.PublicKey = k1.PublicKey

	buffer := sha1.Sum([]byte("Monkey!"))
	hashed := buffer[0:20]
	signature, err := s.SignPKCS1v15(crypto.SHA1, hashed)
	if err != nil {
		t.Fatal(err)
	}

	err = rsa.VerifyPKCS1v15((*rsa.PublicKey)(&k1.PublicKey), crypto.SHA1, hashed, signature)
	if err != nil {
		t.Fatal(err)
	}
}
Exemple #12
0
func TestSessionSign(t *testing.T) {

	k, err := rsa.GenerateKey(rand.Reader, 512)

	if err != nil {
		t.Fatal(err)
	}

	buffer := sha1.Sum([]byte("Monkey!"))
	hashed := buffer[0:20]

	t.Log(hashed)

	k1, k2, err := SplitPrivateKey(k)

	if err != nil {
		t.Fatal(err)
	}

	session := Session{k1.PublicKey, []PartialDecryptor{k1, k2}}

	signature, err := session.SignPKCS1v15(crypto.SHA1, hashed)

	if err != nil {
		t.Fatal(err)
	}

	err = rsa.VerifyPKCS1v15(&k.PublicKey, crypto.SHA1, hashed, signature)

	if err != nil {
		t.Fatal(err)
	}
}
Exemple #13
0
func (u *Updater) checkSignature(data, sig []byte) error {
	u.logger.Debug("checkSignature:call")
	defer u.logger.Debug("checkSignature:return")
	hash := sha256.New()
	hash.Write(data)
	return rsa.VerifyPKCS1v15(u.rsaPubKey, crypto.SHA256, hash.Sum(nil), sig)
}
Exemple #14
0
// KeyVerify verifies that a key certification request was genuinely
// provided by the TPM. It takes the certification data, certification
// validation blob, the public half of the AIK, the public half of the key
// to be certified and the nonce used in the original quote request. It then
// verifies that the validation block is a valid signature for the
// certification data, that the certification data matches the certified key
// and that the secrets are the same (in order to avoid replay attacks). It
// returns an error if any stage of the validation fails.
func KeyVerify(data []byte, validation []byte, aikpub []byte, keypub []byte, secret []byte) error {
	n := big.NewInt(0)
	n.SetBytes(aikpub)
	e := 65537

	pKey := rsa.PublicKey{N: n, E: int(e)}

	dataHash := sha1.Sum(data[:])

	err := rsa.VerifyPKCS1v15(&pKey, crypto.SHA1, dataHash[:], validation)
	if err != nil {
		return err
	}

	keyHash := data[43:63]
	nonceHash := data[63:83]

	secretHash := sha1.Sum(secret[:])

	if bytes.Equal(secretHash[:], nonceHash) == false {
		return fmt.Errorf("Secret doesn't match")
	}

	certHash := sha1.Sum(keypub[:])

	if bytes.Equal(certHash[:], keyHash) == false {
		return fmt.Errorf("Key doesn't match")
	}

	return nil
}
Exemple #15
0
func Decrypt() {
    key := Key()
    h, ha := HashAlgorithm()
    encrypted, err := ioutil.ReadFile(EncryptedFile)
    if err != nil {
        log.Fatalf("failed reading encrypted data: %s", err)
    }

    signature, err := ioutil.ReadFile(SignatureFile)
    if err != nil {
        log.Fatalf("failed saving signature data: %s", err)
    }

    if err = rsa.VerifyPKCS1v15(&key.PublicKey, ha, HashMessage(encrypted), signature); err != nil {
        log.Fatalf("message not valid: %s", err)
    } else {
        log.Printf("message is valid!")
    }

    plaintext, err := rsa.DecryptOAEP(h, rand.Reader, key, encrypted, nil)
    if err != nil {
        log.Fatalf("failed decrypting: %s", err)
    }
    log.Printf("decrypted message: %s", plaintext)
}
Exemple #16
0
// Verify the validity of an uuid signature
func (this *Authority) VerifyUuidSignature(uuid string, uuidSignature []byte) (err error) {
	hash := crypto.SHA256.New()
	hash.Write([]byte(uuid))
	digest := hash.Sum(nil)
	err = rsa.VerifyPKCS1v15(&this.privateKey.PublicKey, crypto.SHA256, digest, uuidSignature)
	return
}
Exemple #17
0
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!")
}
Exemple #18
0
func (m *MobilePayNotify) VerifySign() (bool, error) {

	// 待签名数据
	data := m.signStr()
	// Parse public key into rsa.PublicKey
	PEMBlock, _ := pem.Decode([]byte(pubKeyPEM))
	if PEMBlock == nil {
		return false, errors.New("Could not parse Public Key PEM")
	}
	if PEMBlock.Type != "PUBLIC KEY" {
		return false, errors.New("Found wrong key type")
	}
	pubkey, err := x509.ParsePKIXPublicKey(PEMBlock.Bytes)
	if err != nil {
		return false, err
	}

	// compute the sha1
	h := sha1.New()
	h.Write([]byte(data))

	signature, err := base64.StdEncoding.DecodeString(m.Sign)
	if err != nil {
		return false, err
	}

	// Verify
	err = rsa.VerifyPKCS1v15(pubkey.(*rsa.PublicKey), crypto.SHA1, h.Sum(nil), signature)
	if err != nil {
		return false, err
	}

	return true, nil
}
Exemple #19
0
// VerifySignature verifies in app billing signature.
// You need to prepare a public key for your Android app's in app billing
// at https://play.google.com/apps/publish/
func VerifySignature(base64EncodedPublicKey string, receipt []byte, signature string) (isValid bool, err error) {
	// prepare public key
	decodedPublicKey, err := base64.StdEncoding.DecodeString(base64EncodedPublicKey)
	if err != nil {
		return false, fmt.Errorf("failed to decode public key")
	}
	publicKeyInterface, err := x509.ParsePKIXPublicKey(decodedPublicKey)
	if err != nil {
		return false, fmt.Errorf("failed to parse public key")
	}
	publicKey, _ := publicKeyInterface.(*rsa.PublicKey)

	// generate hash value from receipt
	hasher := sha1.New()
	hasher.Write(receipt)
	hashedReceipt := hasher.Sum(nil)

	// decode signature
	decodedSignature, err := base64.StdEncoding.DecodeString(signature)
	if err != nil {
		return false, fmt.Errorf("failed to decode signature")
	}

	// verify
	if err := rsa.VerifyPKCS1v15(publicKey, crypto.SHA1, hashedReceipt, decodedSignature); err != nil {
		return false, nil
	}

	return true, nil
}
Exemple #20
0
func (m *SigningMethodRS256) Verify(signingString, signature string, key []byte) (err error) {
	// Key
	var sig []byte
	if sig, err = DecodeSegment(signature); err == nil {
		var block *pem.Block
		if block, _ = pem.Decode(key); block != nil {
			var parsedKey interface{}
			if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
				parsedKey, err = x509.ParseCertificate(block.Bytes)
			}
			if err == nil {
				if rsaKey, ok := parsedKey.(*rsa.PublicKey); ok {
					hasher := sha256.New()
					hasher.Write([]byte(signingString))

					err = rsa.VerifyPKCS1v15(rsaKey, crypto.SHA256, hasher.Sum(nil), sig)
				} else if cert, ok := parsedKey.(*x509.Certificate); ok {
					err = cert.CheckSignature(x509.SHA256WithRSA, []byte(signingString), sig)
				} else {
					err = errors.New("Key is not a valid RSA public key")
				}
			}
		} else {
			err = errors.New("Could not parse key data")
		}
	}
	return
}
Exemple #21
0
func (svc *GoPushService) checkAuth(r *http.Request, body []byte) bool {
	v, _ := url.ParseQuery(r.URL.RawQuery)
	mail := v.Get("mail")
	if mail == "" {
		return false
	}

	authheader := r.Header.Get("Authorization")
	if authheader == "" || authheader[0:len(svc.authName)] != svc.authName {
		return false
	}
	signature := authheader[len(svc.authName):]

	h := sha1.New()
	h.Write(body)
	digest := h.Sum(nil)

	sig, _ := hex.DecodeString(signature)

	pubkey := svc.backend.GetPublicKey(mail)

	if pubkey == nil {
		return false
	}

	err := rsa.VerifyPKCS1v15(pubkey, crypto.SHA1, digest, sig)

	return err == nil
}
Exemple #22
0
//这个接口应该和php版的openssl_verify在使用rsa公钥的时候有完全相同的输入输出,加密的坑简直太多了..
//msg是需要验证签名的消息,sig是签名之后生成的
func RsaOpensslVerify(pub *rsa.PublicKey, h crypto.Hash, msg []byte, sig []byte) (err error) {
	h1 := h.New()
	h1.Write(msg)
	digest := h1.Sum(nil)
	err = rsa.VerifyPKCS1v15(pub, h, digest, sig)
	return
}
Exemple #23
0
// verify the message text against signature using the public key
// in PubtktAuth. Expects the signature to be base64 encoded.
// Returns true if the signature is valid, false otherwise
func (pa *PubtktAuth) verifySig(text, signature string) bool {
	sig, err := base64.StdEncoding.DecodeString(signature)
	if err != nil {
		log.Println("problem decoding sig", err)
		return false
	}
	h := sha1.New()
	h.Write([]byte(text))
	digest := h.Sum(nil)

	// This is inspired by the crypto/x509 standard library
	switch pub := pa.publicKey.(type) {
	case *rsa.PublicKey:
		return nil == rsa.VerifyPKCS1v15(pub, crypto.SHA1, digest, sig)
	case *dsa.PublicKey:
		dsaSig := new(dsaSignature)
		if _, err := asn1.Unmarshal(sig, dsaSig); err != nil {
			// log.Println("problem decoding dsa", err)
			return false
		}
		if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
			// log.Println("509: DSA signature contained zero or negative values")
			return false
		}
		return dsa.Verify(pub, digest, dsaSig.R, dsaSig.S)
	}

	return false
}
Exemple #24
0
func (vr *VerifyRequest) VerifySignature() bool {
	armorData := reArmor(vr.CamliSig)
	block, _ := armor.Decode([]byte(armorData))
	if block == nil {
		return vr.fail("Can't parse camliSig armor")
	}
	buf := bytes.NewBuffer(block.Bytes)
	p, err := packet.ReadPacket(buf)
	if err != nil {
		return vr.fail("Error reading PGP packet from camliSig")
	}
	sig, ok := p.(packet.SignaturePacket)
	if !ok {
		return vr.fail("PGP packet isn't a signature packet")
	}
	if sig.Hash != packet.HashFuncSHA1 {
		return vr.fail("I can only verify SHA1 signatures")
	}
	if sig.SigType != packet.SigTypeBinary {
		return vr.fail("I can only verify binary signatures")
	}
	hash := sha1.New()
	hash.Write(vr.bp) // payload bytes
	hash.Write(sig.HashSuffix)
	hashBytes := hash.Sum()
	if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
		return vr.fail("hash tag doesn't match")
	}
	err = rsa.VerifyPKCS1v15(&vr.PublicKeyPacket.PublicKey, rsa.HashSHA1, hashBytes, sig.Signature)
	if err != nil {
		return vr.fail(fmt.Sprintf("bad signature: %s", err))
	}
	return true
}
// VerifyGoogleIDToken is
func VerifyGoogleIDToken(authToken string, certs *Certs, aud string) *TokenInfo {
	header, payload, signature, messageToSign := divideAuthToken(authToken)

	tokeninfo := getTokenInfo(payload)
	var niltokeninfo *TokenInfo
	//fmt.Println(tokeninfo)
	if aud != tokeninfo.Aud {
		err := errors.New("Token is not valid, Audience from token and certificate don't match")
		fmt.Printf("Error verifying key %s\n", err.Error())
		return niltokeninfo
	}
	if (tokeninfo.Iss != "accounts.google.com") && (tokeninfo.Iss != "https://accounts.google.com") {
		err := errors.New("Token is not valid, ISS from token and certificate don't match")
		fmt.Printf("Error verifying key %s\n", err.Error())
		return niltokeninfo
	}
	if !checkTime(tokeninfo) {
		err := errors.New("Token is not valid, Token is expired.")
		fmt.Printf("Error verifying key %s\n", err.Error())
		return niltokeninfo
	}

	key, err := choiceKeyByKeyID(certs.Keys, getAuthTokenKeyID(header))
	if err != nil {
		fmt.Printf("Error verifying key %s\n", err.Error())
		return niltokeninfo
	}
	pKey := rsa.PublicKey{N: a5(urlsafeB64decode(key.N)), E: a4(a2(urlsafeB64decode(key.E)))}
	err = rsa.VerifyPKCS1v15(&pKey, crypto.SHA256, messageToSign, signature)
	if err != nil {
		fmt.Printf("Error verifying key %s\n", err.Error())
		return niltokeninfo
	}
	return tokeninfo
}
Exemple #26
0
// Verify implements the Verify method from SigningMethod.
// For this signing method, must be an *rsa.PublicKey.
func (m *SigningMethodRSA) Verify(raw []byte, sig Signature, key interface{}) error {
	rsaKey, ok := key.(*rsa.PublicKey)
	if !ok {
		return ErrInvalidKey
	}
	return rsa.VerifyPKCS1v15(rsaKey, m.Hash, m.sum(raw), sig)
}
Exemple #27
0
// Verify checks that the given file and its key derivation salt are unaltered.
func (m *MutableFile) Verify() (bool, error) {
	if m.Cap.vk == nil {
		return false, CapabilityError
	}

	if _, ok := m.Cap.vk.(*rsa.PublicKey); !ok {
		return false, errors.New("semiprivate: VK is not an RSA pubkey")
	}

	filePath := path.Join(m.storageDir, m.filename)
	rawFile, err := ioutil.ReadFile(filePath)
	if err != nil {
		return false, err
	}

	// TODO: marshaling scheme should scare me less
	sigSize := AsymmetricKeySize / 8
	sigOffset := len(rawFile) - sigSize
	signature := rawFile[sigOffset : sigOffset+sigSize]

	// for generating EK from RK
	// fileSalt := rawFile[:SaltSize]

	// remember this is hashing all of salt|nonce|ciphertext|tag
	hashData := rawFile[:sigOffset]
	hashed := sha256.Sum256(hashData)

	err = rsa.VerifyPKCS1v15(m.Cap.vk.(*rsa.PublicKey), crypto.SHA256, hashed[:], signature)
	if err == nil {
		return true, nil
	} else {
		return false, err
	}
}
Exemple #28
0
// Verify does the actual verification
func (v RSAPKCS1v15Verifier) Verify(key data.PublicKey, sig []byte, msg []byte) error {
	// will return err if keytype is not a recognized RSA type
	pubKey, err := getRSAPubKey(key)
	if err != nil {
		return err
	}
	digest := sha256.Sum256(msg)

	rsaPub, ok := pubKey.(*rsa.PublicKey)
	if !ok {
		logrus.Debugf("value was not an RSA public key")
		return ErrInvalid
	}

	if rsaPub.N.BitLen() < minRSAKeySizeBit {
		logrus.Debugf("RSA keys less than 2048 bits are not acceptable, provided key has length %d.", rsaPub.N.BitLen())
		return ErrInvalidKeyLength{msg: fmt.Sprintf("RSA key must be at least %d bits.", minRSAKeySizeBit)}
	}

	if len(sig) < minRSAKeySizeByte {
		logrus.Debugf("RSA keys less than 2048 bits are not acceptable, provided signature has length %d.", len(sig))
		return ErrInvalid
	}

	if err = rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, digest[:], sig); err != nil {
		logrus.Errorf("Failed verification: %s", err.Error())
		return ErrInvalid
	}
	return nil
}
// VerifySignatureV3 returns nil iff sig is a valid signature, made by this
// public key, of the data hashed into signed. signed is mutated by this call.
func (pk *PublicKeyV3) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) {
	if !pk.CanSign() {
		return errors.InvalidArgumentError("public key cannot generate signatures")
	}

	suffix := make([]byte, 5)
	suffix[0] = byte(sig.SigType)
	binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix()))
	signed.Write(suffix)
	hashBytes := signed.Sum(nil)

	if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
		return errors.SignatureError("hash tag doesn't match")
	}

	if pk.PubKeyAlgo != sig.PubKeyAlgo {
		return errors.InvalidArgumentError("public key and signature use different algorithms")
	}

	switch pk.PubKeyAlgo {
	case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
		if err = rsa.VerifyPKCS1v15(pk.PublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes); err != nil {
			return errors.SignatureError("RSA verification failure")
		}
		return
	default:
		// V3 public keys only support RSA.
		panic("shouldn't happen")
	}
	panic("unreachable")
}
Exemple #30
0
func TestSignEncodedPolicy(t *testing.T) {
	p := NewCannedPolicy("https://example.com/a", testTime)
	_, jsonPolicy, err := encodePolicy(p)
	if err != nil {
		t.Fatalf("Unexpected policy encode error, %#v", err)
	}

	r := newRandomReader(rand.New(rand.NewSource(1)))

	privKey, err := rsa.GenerateKey(r, 1024)
	if err != nil {
		t.Fatalf("Unexpected priv key error, %#v", err)
	}

	b64Signature, err := signEncodedPolicy(r, jsonPolicy, privKey)
	if err != nil {
		t.Fatalf("Unexpected policy sign error, %#v", err)
	}

	hash := sha1.New()
	if _, err := bytes.NewReader(jsonPolicy).WriteTo(hash); err != nil {
		t.Fatalf("Unexpected hash error, %#v", err)
	}

	decodedSig, err := base64.StdEncoding.DecodeString(string(b64Signature))
	if err != nil {
		t.Fatalf("Unexpected base64 decode signature, %#v", err)
	}

	if err := rsa.VerifyPKCS1v15(&privKey.PublicKey, crypto.SHA1, hash.Sum(nil), decodedSig); err != nil {
		t.Fatalf("Unable to verify signature, %#v", err)
	}
}