• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang rsa.DecryptPKCS1v15函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中crypto/rsa.DecryptPKCS1v15函数的典型用法代码示例。如果您正苦于以下问题:Golang DecryptPKCS1v15函数的具体用法?Golang DecryptPKCS1v15怎么用?Golang DecryptPKCS1v15使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了DecryptPKCS1v15函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: DecryptRSA

//DecryptRSA decrypt given []byte with RSA algorithm
func DecryptRSA(data []byte) []byte {
	if data == 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)
	decrypted := make([]byte, 0, len(data))
	for i := 0; i < len(data); i += 128 {
		if i+128 < len(data) {
			partial, err1 := rsa.DecryptPKCS1v15(rand.Reader, priv, data[i:i+128])
			if err1 != nil {
				return nil
			}
			decrypted = append(decrypted, partial...)
		} else {
			partial, err1 := rsa.DecryptPKCS1v15(rand.Reader, priv, data[i:])
			if err1 != nil {
				return nil
			}
			decrypted = append(decrypted, partial...)
		}
	}
	return decrypted
}
开发者ID:jameswei,项目名称:zmopenapi-sdk-golang,代码行数:36,代码来源:crypto_util.go


示例2: handleEncryptionResponse

func (cem *clientEncryptionManager) handleEncryptionResponse(packet *LS1EncryptionResponsePacket) (err error) {
	cem.sharedSecret, err = rsa.DecryptPKCS1v15(crand.Reader, cem.gem.privateKey, packet.EncryptedSharedSecret)
	if err != nil {
		return err
	}

	returnedVerifyToken, err := rsa.DecryptPKCS1v15(crand.Reader, cem.gem.privateKey, packet.EncryptedVerifyToken)
	if err != nil {
		return err
	}

	if len(cem.verifyToken) != len(returnedVerifyToken) {
		return fmt.Errorf("Authentication failure")
	}

	var diff uint8
	for i := 0; i < len(cem.verifyToken); i++ {
		diff |= cem.verifyToken[i] ^ returnedVerifyToken[i]
	}

	if diff != 0 {
		return fmt.Errorf("Authentication failure")
	}

	return nil
}
开发者ID:kierdavis,项目名称:proxy,代码行数:26,代码来源:clientencryption.go


示例3: HandleFC

// HandleFC handles incoming requests of packet 0xFC: EncryptionKeyResponse
func HandleFC(server *Server, sender *player.Player) {
	pkt := new(packet.EncryptionKeyResponse)
	pkt.ReadFrom(sender.Conn)

	// Decrypt shared secret and token with server's private key.
	var secret, token []byte
	// var err error
	secret, _ = rsa.DecryptPKCS1v15(rand.Reader, server.PrivateKey(), pkt.Secret)
	token, _ = rsa.DecryptPKCS1v15(rand.Reader, server.PrivateKey(), pkt.Token)

	// Ensure token matches
	if !bytes.Equal(token, sender.Token) {
		log.Println("Tokens don't match.")
		r := &packet.Disconnect{Reason: ReasonPiratedGame}
		r.WriteTo(sender.Conn)
		return
	}

	// Ensure player is legit
	if !server.CheckUser(sender.Name, secret) {
		log.Println("Failed to verify username!")
		r := packet.Disconnect{"Failed to verify username!"}
		r.WriteTo(sender.Conn)
		return
	}

	// Send empty EncryptionKeyResponse
	r := new(packet.EncryptionKeyResponse)
	r.WriteTo(sender.Conn)

	// Start AES/CFB8 stream encryption
	sender.OnlineMode(true, secret)
	log.Println("Enabling encryption.")
}
开发者ID:KellyLSB,项目名称:minero-go,代码行数:35,代码来源:handle_fc.go


示例4: TestCanNegotiateEncryptedConnection

func TestCanNegotiateEncryptedConnection(t *testing.T) {
	c, rbuf, wbuf := createConnection()
	sessionRecorder := session.NewRecorderClient()
	priv, pub, err := createPPK()
	Expect(t, err, ToBeNil)
	verifyToken := []byte{1, 2, 3, 4}

	// server gets handshake, sends EKRequest
	Expect(t, rbuf, ToWritePacket, &EncryptionKeyRequest{
		ServerID:    "-", // no user verification server ?
		PublicKey:   pub,
		VerifyToken: verifyToken,
	})
	// server gets EKResponse, returns empty EKResponse
	Expect(t, rbuf, ToWritePacket, &EncryptionKeyResponse{
		SharedSecret: []byte{},
		VerifyToken:  []byte{},
	})
	// server promotes to encrypted socket

	handshake := &Handshake{
		Version:  47,
		Username: "Joe Smoe",
		Hostname: "localhost",
		Port:     25565,
	}
	secret := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
	err = EstablishEncryptedConnection(c, handshake, secret, sessionRecorder)

	Expect(t, err, ToBeNil)

	// client should send handshake
	Expect(t, wbuf, ToReadPacket, handshake)
	// client should send EKResponse
	p, err := wbuf.ReadPacket()
	Expect(t, err, ToBeNil)
	ekRes, ok := p.(*EncryptionKeyResponse)
	Expect(t, ok, ToBeTrue)

	// we need to decrypt the fields
	dVerifyToken, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ekRes.VerifyToken)
	Expect(t, err, ToBeNil)
	Expect(t, dVerifyToken, ToEqual, verifyToken)
	dSecret, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ekRes.SharedSecret)
	Expect(t, err, ToBeNil)
	Expect(t, dSecret, ToEqual, secret)

	// shouldn't have any extra data
	Expect(t, rbuf.IsEmpty(), ToBeTrue)
	Expect(t, wbuf.IsEmpty(), ToBeTrue)
	// connection should be modified
	Expect(t, c.IsEncrypted(), ToBeTrue)
	Expect(t, c.ServerID, ToBe, "-")
	Expect(t, c.Encryption.SharedKey, ToEqual, secret)
}
开发者ID:jeffh,项目名称:mc,代码行数:55,代码来源:connection_test.go


示例5: TestDecrypt

func TestDecrypt(t *testing.T) {
	block, rest := pem.Decode(testData[0].privateKey)

	if len(rest) > 0 {
		t.Error("extra data")
	}

	der, err := x509.DecryptPEMBlock(block, []byte(testData[0].passphrase))

	if err != nil {
		t.Error("decrypt failed: ", err)
	}

	var privateKey *rsa.PrivateKey
	if privateKey, err = x509.ParsePKCS1PrivateKey(der); err != nil {
		t.Error("private key failed: ", err)
	}

	b, _ := base64.StdEncoding.DecodeString(testData[0].encryptedMessage)

	decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, b)

	if err != nil {
		t.Error("failed to decrypt, ", err)
	}

	assert.Equal(t, testData[0].decryptedMessage, string(decrypted), "should be the same")
}
开发者ID:releasifier,项目名称:releasifier,代码行数:28,代码来源:rsa_test.go


示例6: HybridDecrypt

func HybridDecrypt(encryptedPrivateKey []byte, awsRegion string, encryptionContext map[string]*string, base64EncryptedText string) (string, error) {
	sections := strings.Split(base64EncryptedText, hybridDelimiter)

	encryptedSecretKey, err := base64.StdEncoding.DecodeString(sections[0])
	if err != nil {
		log.Fatal("Error decoding secret key" + err.Error())
	}

	aesEncryptedText := sections[1]

	privateKey, err := getPrivateKey(encryptedPrivateKey, awsRegion, encryptionContext)
	if err != nil {
		log.Fatal("Can't get private key - " + err.Error())
	}

	secretKey, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encryptedSecretKey)
	if err != nil {
		log.Fatal("Can't decrypt AES key - " + err.Error())
	}

	plaintext, err := AesDecrypt(secretKey, aesEncryptedText)
	if err != nil {
		log.Fatal("Can't decrypt plaintext - " + err.Error())
	}

	return plaintext, nil
}
开发者ID:gravieinc,项目名称:aws-crypto-tools-go,代码行数:27,代码来源:hybrid.go


示例7: TestGeneratePem_GeneratePemThenCheckIfValidPrivateKey

func TestGeneratePem_GeneratePemThenCheckIfValidPrivateKey(t *testing.T) {
	privateKey := PrivateKey()
	privatePem := GeneratePrivatePem(privateKey)
	pemBlock, _ := pem.Decode(privatePem)
	if pemBlock == nil {
		t.Fatal("The pem key didn't transfer back into a block")
	}
	validKey, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
	if err != nil {
		t.Fatal("The parser failed to create a key")
	}
	output := validKey.Validate()
	if output != nil {
		t.Fatal("The key that was created is not valid")
	}

	snippet := "Hello, world!"
	publicKey := privateKey.PublicKey
	publicEncrypt, _ := rsa.EncryptPKCS1v15(rand.Reader, &publicKey, []byte(snippet))

	privateDecrypt, err := rsa.DecryptPKCS1v15(rand.Reader, validKey, publicEncrypt)
	if err != nil {
		t.Fatal("Something went wrong in the decryption of publicEncrypt: ", err)
	}

	if string(privateDecrypt) != snippet {
		t.Fatal("Something didn't work in: ", privateDecrypt)
	}
}
开发者ID:amaxwellblair,项目名称:coinage_go,代码行数:29,代码来源:keyGenerator_test.go


示例8: main

func main() {
	var primes []uint64 = prime.PrimeSieveBatch{BatchSize: 100}.GetPrimes(10000)
	var p, q uint64 = /*uint64(104723), uint64(104729) */ primes[len(primes)-2], primes[len(primes)-1]
	fmt.Println(p, q)
	var mod int64 = int64(p * q)
	fmt.Println(mod)
	var puk, prk = /*int(65537), uint64(10195862609) */ KeyGenerator1{}.KeyGen(p, q)
	fmt.Println(puk, prk)

	b := []byte("Hi")
	var pub rsa.PublicKey = rsa.PublicKey{N: big.NewInt(mod), E: puk}
	var priv rsa.PrivateKey = rsa.PrivateKey{PublicKey: pub}
	priv.D = big.NewInt(int64(prk))
	priv.Primes = []*big.Int{big.NewInt(int64(p)), big.NewInt(int64(q))}

	fmt.Println(len(b))
	fmt.Printf("% x\n", b)

	//h := md5.New()
	enc, erre := rsa.EncryptPKCS1v15(rand.Reader, &pub, b)
	//h.Reset()
	dec, errd := rsa.DecryptPKCS1v15(rand.Reader, &priv, b)

	//fmt.Println(64 - 11)
	fmt.Printf("%s\n", erre)
	fmt.Printf("%s\n", errd)
	fmt.Printf("% x\n", enc)
	fmt.Printf("% x\n", dec)
}
开发者ID:frankbryce,项目名称:crypto-explore,代码行数:29,代码来源:main.go


示例9: RSADecrypt

// RSADecrypt RSA解密
func RSADecrypt(privateKey, data []byte) ([]byte, error) {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error")
	}
	pri, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	maxLen := (pri.PublicKey.N.BitLen() + 7) / 8 // 每次解密 密文的最大长度

	var message []byte
	// 计算明文的最大长度(解密后明文要比密文短,maxLen-11就是加密是明文的最大长度)
	if m := len(data); m%maxLen == 0 {
		message = make([]byte, 0, m/maxLen*(maxLen-11))
	} else {
		message = make([]byte, 0, (m/maxLen+1)*(maxLen-11))
	}
	for {
		if l := len(data); l == 0 {
			break
		} else if l < maxLen {
			maxLen = l
		}
		d, err := rsa.DecryptPKCS1v15(rand.Reader, pri, data[0:maxLen])
		if err != nil {
			return nil, err
		}
		data = data[maxLen:]
		message = append(message, d...)
	}
	return message, nil
}
开发者ID:zhangyuchen0411,项目名称:goutil,代码行数:34,代码来源:rsa.go


示例10: RsaDecrypt

//********私钥解密  注意:相对路径读取还没解决,这块不能出现在客户端,否则暴露私钥
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	/*file2, err := os.Open("D:/myproject/src/beeim/cfg/private.pem")
	if err != nil {
		panic(err)
	}
	defer file2.Close()
	privateKey, err := ioutil.ReadAll(file2)
	if err != nil {
		panic(err)
	}*/
	privateKey := []byte(`-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCbmNv4mBsuPb4xzuUwT2TxEbjGva76zLrF//NRiUKV/T8mKtfv
/R+Q+7FGwYkZbDNl5bO0UF0MR69u8ZE1cBAzn74zJGqQVs9QrRgp3VTYM/9s8nOv
ogcz6+l1amEY+djV3iztHOxyptl1Eq8d3r82kcwfybxRlNMfwNhT7VpvqQIDAQAB
AoGABdcrCp3LB2VR6lS1zaZtR48+vFcKZmeg6yW8YGcilLa41BnvmRaLRMnt0ZYa
K1YgZ8bDhBUwKPHX5/YxWSwnr3ll0yVKYPw310djZduJT/XSy2ugEpfhZEyKEKxE
sxArAI25IWHWnkKbJ1d6AfR0Rvac5v5O5rkpAiFWCXm633ECQQDBNWgqiSIOB4LQ
SkbMdElTOfv5/lPmjDyh2HgjRtUFs6nIDp9aJeJ4f5aZWN3trFJRTqku72dxclYi
8eSimqqjAkEAzio+ydoeF5NoYBBb5Gx5Uooz8dncxyMdzPE6OaOza9AuF5uw8CXg
ZFFXVPtbKJ7QzZ3DsenyCm4uhifpR8yNQwJAY8rsBJxUBJ8IiAD1VIDzppMafONJ
/piMcKPYWZAqUwmbNgOndu5+bPKpnIb0CeCpm+lfJSjuawA9UUtTZlEwtQJBAIT0
16NjqE56ATEau7h3gFKL0G4jm29NpVVbKLqtaPOZwW/2N0jYlHr9vj2PEL4ElhJU
sTUW88JoRla8fISSVXMCQQCGt4L8msE7Hb1yLJkIAE3SJXS6y6paFuBbensjKHEK
MlVlIJO2Pwz66P+w/Q+AGGGF6KvxIGViXM9ALZcP3ZQ8
-----END RSA PRIVATE KEY-----`)
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
开发者ID:HYQMartin,项目名称:mybeeim,代码行数:36,代码来源:rsa.go


示例11: Unwrap

func (alg *RsaPkcs1v15) Unwrap(encryptedCek []byte, key interface{}, cekSizeBits int, header map[string]interface{}) (cek []byte, err error) {
	if privKey, ok := key.(*rsa.PrivateKey); ok {
		return rsa.DecryptPKCS1v15(rand.Reader, privKey, encryptedCek)
	}

	return nil, errors.New("RsaPkcs1v15.Unwrap(): expected key to be '*rsa.PrivateKey'")
}
开发者ID:useidel,项目名称:notary,代码行数:7,代码来源:rsa_pkcs1v15.go


示例12: decryptPasswordDataWithPrivateKey

func decryptPasswordDataWithPrivateKey(passwordData string, pemBytes []byte) (string, error) {
	encryptedPasswd, err := base64.StdEncoding.DecodeString(passwordData)
	if err != nil {
		return "", err
	}

	block, _ := pem.Decode(pemBytes)
	var asn1Bytes []byte
	if _, ok := block.Headers["DEK-Info"]; ok {
		return "", errors.New("encrypted private key isn't yet supported")
		/*
			asn1Bytes, err = x509.DecryptPEMBlock(block, password)
			if err != nil {
				return "", err
			}
		*/
	} else {
		asn1Bytes = block.Bytes
	}

	key, err := x509.ParsePKCS1PrivateKey(asn1Bytes)
	if err != nil {
		return "", err
	}

	out, err := rsa.DecryptPKCS1v15(nil, key, encryptedPasswd)
	if err != nil {
		return "", err
	}

	return string(out), nil
}
开发者ID:c12simple,项目名称:packer,代码行数:32,代码来源:step_get_password.go


示例13: Decrypt

// Decrypt decrypts an encrypted session key with the given private key. The
// private key must have been decrypted first.
// If config is nil, sensible defaults will be used.
func (e *EncryptedKey) Decrypt(priv *PrivateKey, config *Config) error {
	var err error
	var b []byte

	// TODO(agl): use session key decryption routines here to avoid
	// padding oracle attacks.
	switch priv.PubKeyAlgo {
	case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly:
		b, err = rsa.DecryptPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), e.encryptedMPI1.bytes)
	case PubKeyAlgoElGamal:
		c1 := new(big.Int).SetBytes(e.encryptedMPI1.bytes)
		c2 := new(big.Int).SetBytes(e.encryptedMPI2.bytes)
		b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2)
	default:
		err = errors.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo)))
	}

	if err != nil {
		return err
	}

	e.CipherFunc = CipherFunction(b[0])
	e.Key = b[1 : len(b)-2]
	expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1])
	checksum := checksumKeyMaterial(e.Key)
	if checksum != expectedChecksum {
		return errors.StructuralError("EncryptedKey checksum incorrect")
	}

	return nil
}
开发者ID:ContiGuy,项目名称:conti-gui,代码行数:34,代码来源:encrypted_key.go


示例14: _passwordDecoding

func _passwordDecoding(encodedpassword, passpharse []byte, priblock *pem.Block) (password []byte, err error) {
	//decode with base64
	_encodedpassword, err := base64.StdEncoding.DecodeString(string(encodedpassword))
	if err != nil {
		return
	}

	//compare to private key
	priByte, err := x509.DecryptPEMBlock(priblock, passpharse)
	if err != nil {
		return
	}

	pri, err := x509.ParsePKCS1PrivateKey(priByte)
	if err != nil {
		return
	}
	//decode with rsa
	password, err = rsa.DecryptPKCS1v15(rand.Reader, pri, _encodedpassword)

	if err != nil {
		return
	}

	return
}
开发者ID:wulinxu,项目名称:KeyAdmin-go,代码行数:26,代码来源:passwordadmin.go


示例15: _passwordListDecoding

func _passwordListDecoding(encodedpassword [][]byte, passpharse []byte, priblock *pem.Block) (password [][]byte, err error) {
	//decode with base64
	encodedpasswordList := make([][]byte, len(encodedpassword))
	for i, e := range encodedpassword {
		encodedpasswordList[i], err = base64.StdEncoding.DecodeString(string(e))
		if err != nil {
			return
		}
	}

	//compare to private key
	priByte, err := x509.DecryptPEMBlock(priblock, passpharse)
	if err != nil {
		return
	}

	pri, err := x509.ParsePKCS1PrivateKey(priByte)
	if err != nil {
		return
	}
	//decode with rsa
	password = make([][]byte, len(encodedpasswordList))
	for i, e := range encodedpasswordList {
		password[i], err = rsa.DecryptPKCS1v15(rand.Reader, pri, e)
	}

	if err != nil {
		return
	}

	return
}
开发者ID:wulinxu,项目名称:KeyAdmin-go,代码行数:32,代码来源:passwordadmin.go


示例16: Key

func (c *Cipher) Key(key *rsa.PrivateKey) ([]uint8, error) {
	data := make([]uint8, len(c.KeyData))
	for i := range data {
		data[i] = c.KeyData[len(c.KeyData)-i-1]
	}

	return rsa.DecryptPKCS1v15(nil, key, data)
}
开发者ID:keyphact,项目名称:pso2-go,代码行数:8,代码来源:cipher.go


示例17: RSADecrypt

// RSADecrypt decrypts content by a private key
func RSADecrypt(keyBytes []byte, contentBytes []byte) ([]byte, error) {
	privKey, err := getPrivKey(keyBytes)
	if err != nil {
		return nil, err
	}

	return rsa.DecryptPKCS1v15(rand.Reader, privKey, contentBytes)
}
开发者ID:pombredanne,项目名称:dockyard,代码行数:9,代码来源:common.go


示例18: GetNakedKey

func GetNakedKey(cipher string) ([]byte, error) {
	rawCipher, err := base64.StdEncoding.DecodeString(cipher)
	if err != nil {
		return nil, err
	}

	InitPrivKey()
	return rsa.DecryptPKCS1v15(rand.Reader, privateKey, rawCipher)
}
开发者ID:applepi-icpc,项目名称:icarus,代码行数:9,代码来源:cipher.go


示例19: decryptSessionKey

func decryptSessionKey(skey []byte, privkey *rsa.PrivateKey) (session_key []byte) {
	verbose("Decrypting session key...", 2)

	session_key, err := rsa.DecryptPKCS1v15(rand.Reader, privkey, skey)
	if err != nil {
		fail("Unable to decrypt session key.")
	}

	return
}
开发者ID:fatman2021,项目名称:jass,代码行数:10,代码来源:jass.go


示例20: RsaDecrypt

// 解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
开发者ID:jmptrader,项目名称:goexample,代码行数:12,代码来源:rsa.go



注:本文中的crypto/rsa.DecryptPKCS1v15函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang rsa.DecryptPKCS1v15SessionKey函数代码示例发布时间:2022-05-24
下一篇:
Golang rsa.DecryptOAEP函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap