本文整理汇总了Golang中crypto/rsa.EncryptPKCS1v15函数的典型用法代码示例。如果您正苦于以下问题:Golang EncryptPKCS1v15函数的具体用法?Golang EncryptPKCS1v15怎么用?Golang EncryptPKCS1v15使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了EncryptPKCS1v15函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
示例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
}
示例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
}
示例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
}
示例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
}
}
示例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)
}
示例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)
}
示例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)
}
}
示例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
}
示例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
}
}
示例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
}
示例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
}
示例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)
}
示例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)
}
示例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
}