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

Golang rsa.EncryptPKCS1v15函数代码示例

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

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



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

示例1: EncryptRSA

//EncryptRSA encrypt given data with RSA algorithm
func EncryptRSA(data []byte) []byte {
	if data == nil {
		return nil
	}
	publicKey := []byte(PublicKey)
	if !ginutil.IsProduction() {
		publicKey = []byte(TestPublicKey)
	}
	block, _ := pem.Decode(publicKey)
	if block == nil {
		return nil
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil
	}
	pub := pubInterface.(*rsa.PublicKey)
	encrypted := make([]byte, 0, len(data))
	for i := 0; i < len(data); i += 117 {
		if i+117 < len(data) {
			partial, err1 := rsa.EncryptPKCS1v15(rand.Reader, pub, data[i:i+117])
			if err1 != nil {
				return nil
			}
			encrypted = append(encrypted, partial...)
		} else {
			partial, err1 := rsa.EncryptPKCS1v15(rand.Reader, pub, data[i:])
			if err1 != nil {
				return nil
			}
			encrypted = append(encrypted, partial...)
		}
	}
	return encrypted
}
开发者ID:jameswei,项目名称:zmopenapi-sdk-golang,代码行数:36,代码来源:crypto_util.go


示例2: genKey

// Generates a symmetric key and encrypts the verification token
func (client *Client) genKey() (err error) {
	if client.DebugWriter != nil {
		fmt.Fprintf(client.DebugWriter, "Decoding public key\n")
	}

	var pki publicKeyInfo
	_, err = asn1.Unmarshal(client.serverKeyMessage, &pki)
	if err != nil {
		return err
	}

	client.serverKey = new(rsa.PublicKey)
	_, err = asn1.Unmarshal(pki.SubjectPublicKey.Bytes, client.serverKey)
	if err != nil {
		return err
	}

	if client.DebugWriter != nil {
		fmt.Fprintf(client.DebugWriter, "Generating encryption key\n")
	}

	/*
		client.sharedSecret = make([]byte, 16)

		_, err = rand.Reader.Read(client.sharedSecret)
		if err != nil {
			return err
		}
	*/

	client.sharedSecret = []byte("1234567812345678")

	if client.DebugWriter != nil {
		fmt.Fprintf(client.DebugWriter, "Encrypting verification token\n")
	}

	client.encryptedVerifyToken, err = rsa.EncryptPKCS1v15(rand.Reader, client.serverKey, client.serverVerifyToken)
	if err != nil {
		return err
	}

	if client.DebugWriter != nil {
		fmt.Fprintf(client.DebugWriter, "Encrypting shared secret\n")
	}

	client.encryptedSharedSecret, err = rsa.EncryptPKCS1v15(rand.Reader, client.serverKey, client.sharedSecret)
	if err != nil {
		return err
	}

	return nil
}
开发者ID:Syfaro,项目名称:mc,代码行数:53,代码来源:server.go


示例3: GenerateCredentials

func GenerateCredentials(username, password, rawPem []byte) (cred string, err error) {
	ms := time.Now().UnixNano() / 1e6
	unixStr := strconv.FormatInt(ms, 10)

	userBase64 := base64.StdEncoding.EncodeToString(username)
	passBase64 := base64.StdEncoding.EncodeToString(password)
	timeBase64 := base64.StdEncoding.EncodeToString([]byte(unixStr))

	formated := fmt.Sprintf("%s:%s:%s", userBase64, passBase64, timeBase64)

	block, _ := pem.Decode(rawPem)
	if block == nil {
		err = errors.New("Could not Decode PEM")
		return
	}

	pubKeyVal, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return
	}

	rsaPubKey, ok := pubKeyVal.(*rsa.PublicKey)
	if !ok {
		err = errors.New("Could not make DER to an RSA PublicKey")
		return
	}

	encr, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPubKey, []byte(formated))
	if err != nil {
		return
	}

	cred = base64.StdEncoding.EncodeToString(encr)
	return
}
开发者ID:gurre,项目名称:nordnet,代码行数:35,代码来源:util.go


示例4: HybridEncrypt

func HybridEncrypt(publicKeyFile []byte, plaintextBytes []byte) (string, error) {
	secretKey := GenerateSecretKey()
	encryptedString, err := AesEncrypt(secretKey, plaintextBytes)
	if err != nil {
		log.Fatal("failed to GcmEncrypt: " + err.Error())
	}

	publicKeyUntyped, err := x509.ParsePKIXPublicKey(publicKeyFile)
	if err != nil {
		log.Fatal("failed to parse certificate: " + err.Error())
	}
	publicKey := publicKeyUntyped.(*rsa.PublicKey)

	encryptedPublicKeyBytes, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, secretKey)
	if err != nil {
		log.Fatal("failed to wrap" + err.Error())
	}

	var buffer bytes.Buffer
	buffer.WriteString(base64.StdEncoding.EncodeToString(encryptedPublicKeyBytes))
	buffer.WriteString(hybridDelimiter)
	buffer.WriteString(encryptedString)

	return buffer.String(), nil
}
开发者ID:gravieinc,项目名称:aws-crypto-tools-go,代码行数:25,代码来源:hybrid.go


示例5: NewDecryptTest

// NewDecryptTest generates an RSA decryption test.
func NewDecryptTest(decrypter crypto.Decrypter) testapi.TestFunc {
	ptxt := []byte("Test Plaintext")
	r := rand.Reader

	return func() (err error) {
		var c, m []byte
		if c, err = rsa.EncryptPKCS1v15(r, decrypter.Public().(*rsa.PublicKey), ptxt); err != nil {
			return
		}

		if m, err = decrypter.Decrypt(r, c, &rsa.PKCS1v15DecryptOptions{}); err != nil {
			return
		}
		if bytes.Compare(ptxt, m) != 0 {
			return errors.New("rsa decrypt failed")
		}

		if m, err = decrypter.Decrypt(r, c, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: len(ptxt)}); err != nil {
			return
		}
		if bytes.Compare(ptxt, m) != 0 {
			return errors.New("rsa decrypt failed")
		}

		if m, err = decrypter.Decrypt(r, c, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: len(ptxt) + 1}); err != nil {
			return
		}
		if bytes.Compare(ptxt, m) == 0 {
			return errors.New("rsa decrypt suceeded despite incorrect SessionKeyLen")
		}
		return nil
	}
}
开发者ID:carriercomm,项目名称:gokeyless,代码行数:34,代码来源:tests.go


示例6: RsaEncrypt

//********公钥加密 注意:os.Open 相对路径会报错,且这一块应打包在客户端
func RsaEncrypt(origData []byte, publicKey []byte) ([]byte, error) {
	/*file1, err := os.Open("D:/myproject/src/beeim/cfg/public.pem")
	if err != nil {
		panic(err)
	}
	defer file1.Close()
	publicKey, err := io util.ReadAll(file1)
	if err != nil {
		panic(err)
	}*/
	/*publicKey := []byte(`-----BEGIN PUBLIC KEY-----
	MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbmNv4mBsuPb4xzuUwT2TxEbjG
	va76zLrF//NRiUKV/T8mKtfv/R+Q+7FGwYkZbDNl5bO0UF0MR69u8ZE1cBAzn74z
	JGqQVs9QrRgp3VTYM/9s8nOvogcz6+l1amEY+djV3iztHOxyptl1Eq8d3r82kcwf
	ybxRlNMfwNhT7VpvqQIDAQAB
	-----END PUBLIC KEY-----`)*/

	block, _ := pem.Decode(publicKey)
	if block == nil {
		return nil, errors.New("public key error")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pub := pubInterface.(*rsa.PublicKey)
	return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}
开发者ID:HYQMartin,项目名称:mybeeim,代码行数:29,代码来源:rsa.go


示例7: EncryptPKCS1v15

func EncryptPKCS1v15(msg []byte) string {
	certPEMBlock, err := ioutil.ReadFile("./key.pem")
	if err != nil {
		log.Fatal("PEM error %v", err)
	}

	var keyDERBlock *pem.Block
	keyDERBlock, certPEMBlock = pem.Decode(certPEMBlock)

	var publickey *rsa.PublicKey
	if key, err := x509.ParsePKIXPublicKey(keyDERBlock.Bytes); err == nil {
		publickey = key.(*rsa.PublicKey)
		log.Printf("got a key")
	}

	encryptedmsg, err := rsa.EncryptPKCS1v15(rand.Reader, publickey, msg)

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

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

	return base64.URLEncoding.EncodeToString(encryptedmsg)
}
开发者ID:mikechack,项目名称:wsrouter,代码行数:27,代码来源:oauth.go


示例8: 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


示例9: RSAEncrypt

// Used for tests. Everytime its load key from file.
func RSAEncrypt(data []byte) ([]byte, error) {
	pathToKey, cfgErr := cfg.GetStr(cfg.STR_KEYS_PATH)
	if cfgErr != nil {
		return nil, cfgErr
	}

	pemData, err := ioutil.ReadFile(pathToKey + "public_key.pem")
	if err != nil {
		return nil, err
	}
	// Extract the PEM-encoded data block
	block, _ := pem.Decode(pemData)
	if block == nil {
		return nil, errors.New("Empty block.")
	}

	// Decode the RSA public key
	key, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pkey := key.(*rsa.PublicKey)
	// Encrypt the data
	out, err := rsa.EncryptPKCS1v15(rand.Reader, pkey, data)
	if err != nil {
		return nil, err
	}

	return out, nil
}
开发者ID:walkline,项目名称:GoMastersLunch,代码行数:31,代码来源:SimpleRSA.go


示例10: EncryptChatMessage

func (c *Controller) EncryptChatMessage() (string, error) {

	var err error

	c.r.ParseForm()

	receiver := c.r.FormValue("receiver")
	message := c.r.FormValue("message")
	if len(message) > 5120 {
		return "", errors.New("incorrect message")
	}

	publicKey, err := c.Single("SELECT public_key_0 FROM users WHERE user_id  =  ?", receiver).Bytes()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	if len(publicKey) > 0 {
		pub, err := utils.BinToRsaPubKey(publicKey)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		enc_, err := rsa.EncryptPKCS1v15(rand.Reader, pub, []byte(message))
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		return utils.JsonAnswer(string(utils.BinToHex(enc_)), "success").String(), nil
	} else {
		return utils.JsonAnswer("Incorrect user_id", "error").String(), nil
	}

}
开发者ID:dzyk,项目名称:dcoin-go,代码行数:32,代码来源:encrypt_chat_message.go


示例11: RSAEncrypt

// RSAEncrypt RSA加密,将消息使用公钥加密后传给对方,由对方使用私钥解密
func RSAEncrypt(publicKey, message []byte) ([]byte, error) {
	block, _ := pem.Decode(publicKey)
	if block == nil {
		return nil, errors.New("public key error")
	}
	pubIntf, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pub := pubIntf.(*rsa.PublicKey)
	maxLen := (pub.N.BitLen()+7)/8 - 11 // 每次加密明文的最大长度

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


示例12: generateClientKeyExchange

func (ka *rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
	preMasterSecret := make([]byte, 48)
	vers := clientHello.vers
	if config.Bugs.RsaClientKeyExchangeVersion != 0 {
		vers = config.Bugs.RsaClientKeyExchangeVersion
	}
	vers = versionToWire(vers, clientHello.isDTLS)
	preMasterSecret[0] = byte(vers >> 8)
	preMasterSecret[1] = byte(vers)
	_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
	if err != nil {
		return nil, nil, err
	}

	encrypted, err := rsa.EncryptPKCS1v15(config.rand(), cert.PublicKey.(*rsa.PublicKey), preMasterSecret)
	if err != nil {
		return nil, nil, err
	}
	ckx := new(clientKeyExchangeMsg)
	if clientHello.vers != VersionSSL30 && !config.Bugs.SSL3RSAKeyExchange {
		ckx.ciphertext = make([]byte, len(encrypted)+2)
		ckx.ciphertext[0] = byte(len(encrypted) >> 8)
		ckx.ciphertext[1] = byte(len(encrypted))
		copy(ckx.ciphertext[2:], encrypted)
	} else {
		ckx.ciphertext = encrypted
	}
	return preMasterSecret, ckx, nil
}
开发者ID:hoangmichel,项目名称:webrtc,代码行数:29,代码来源:key_agreement.go


示例13: 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


示例14: RSAEncrypt

// RSAEncrypt encrypts a content by a public key
func RSAEncrypt(keyBytes []byte, contentBytes []byte) ([]byte, error) {
	pubKey, err := getPubKey(keyBytes)
	if err != nil {
		return nil, err
	}

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


示例15: encryptPreMasterSecret

//See: 7.4.7.1.  RSA-Encrypted Premaster Secret Message
func encryptPreMasterSecret(preMasterSecret []byte, pub *rsa.PublicKey) (*encryptedPreMasterSecretBody, error) {
	out, err := rsa.EncryptPKCS1v15(rand.Reader, pub, preMasterSecret)
	if err != nil {
		return nil, err
	}

	return &encryptedPreMasterSecretBody{out}, nil
}
开发者ID:twstrike,项目名称:toyls,代码行数:9,代码来源:handshake.go


示例16: makeEncryptionResponse

func (sem *serverEncryptionManager) makeEncryptionResponse() (packet *LS1EncryptionResponsePacket, err error) {
	encryptedSharedSecret, err := rsa.EncryptPKCS1v15(crand.Reader, &sem.remotePublicKey, sem.sharedSecret)
	if err != nil {
		return nil, err
	}

	encryptedVerifyToken, err := rsa.EncryptPKCS1v15(crand.Reader, &sem.remotePublicKey, sem.verifyToken)
	if err != nil {
		return nil, err
	}

	packet = &LS1EncryptionResponsePacket{
		EncryptedSharedSecret: encryptedSharedSecret,
		EncryptedVerifyToken:  encryptedVerifyToken,
	}

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


示例17: KeyEncrypt

// KeyEncrypt encrypts the content encryption key using RSA PKCS1v15
func (e RSAPKCSKeyEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) {
	if e.alg != jwa.RSA1_5 {
		return nil, ErrUnsupportedAlgorithm
	}
	encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, e.pubkey, cek)
	if err != nil {
		return nil, err
	}
	return ByteKey(encrypted), nil
}
开发者ID:lestrrat,项目名称:go-jwx,代码行数:11,代码来源:key_encrypt.go


示例18: encrypt

func (e *encrypter) encrypt(pass string) (b string, err error) {
	if e.rand == nil {
		e.rand = rand.Reader
	}
	var data []byte
	if data, err = rsa.EncryptPKCS1v15(e.rand, &e.pk, []byte(pass)); err != nil {
		return
	}
	return "rsa:" + base64.StdEncoding.EncodeToString(data), nil
}
开发者ID:dullgiulio,项目名称:bruto,代码行数:10,代码来源:encrypt.go


示例19: Serialize

// Serializes the vote.
func (vote Vote) Serialize(publicKey *rsa.PublicKey) (*[]byte, error) {
	s := strings.Join([]string{"VOTE", vote.ServiceName, vote.Username, vote.Address, vote.Timestamp, ""}, "\n")
	msg := []byte(s)

	// Encrypt the vote using the supplied public key.
	encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, msg)
	if err != nil {
		return nil, err
	}

	return &encrypted, nil
}
开发者ID:minecrafter,项目名称:go-votifier,代码行数:13,代码来源:protocol.go


示例20: Encrypt

func (u *User) Encrypt(key *rsa.PrivateKey) error {
	if u.Encrypted {
		return nil
	}
	encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, &key.PublicKey, []byte(u.Password))
	if err != nil {
		return err
	}
	u.Password = string(encrypted)
	u.Encrypted = true
	return nil
}
开发者ID:d4l3k,项目名称:upass,代码行数:12,代码来源:crypto.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang rsa.GenerateKey函数代码示例发布时间:2022-05-24
下一篇:
Golang rsa.EncryptOAEP函数代码示例发布时间: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