//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 }
// 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 }
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 }
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 }
// 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 } }
//********公钥加密 注意: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) }
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) }
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) } }
// 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 }
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 } }
// 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 }
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 }
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) }
// 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) }
//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 }
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 }
// 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 }
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 }
// 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 }
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 }
func GenKey() (orig []byte, cipher string) { orig = make([]byte, KeyLength) _, err := rand.Read(orig) checkErr(err) InitPubkey() r, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, orig) checkErr(err) cipher = base64.StdEncoding.EncodeToString(r) return }
func (this *RsaCipher) DoEncrypt(src []byte) ([]byte, error) { block, _ := pem.Decode(this.PubKey) 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, src) }
// 加密 func RsaEncrypt(origData []byte) ([]byte, error) { 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) }
// rsa and then base64, operate on []byte func RsaBase64(msg_to_enc []byte) (msg_encrypted string, err error) { private_key := get_private_key() publick_key := private_key.PublicKey msg_rsaed, err := rsa.EncryptPKCS1v15(rand.Reader, &publick_key, msg_to_enc) if err != nil { return } msg_rsaed_base64ed := base64.StdEncoding.EncodeToString(msg_rsaed) msg_encrypted = msg_rsaed_base64ed return }
func (alg *RsaPkcs1v15) WrapNewKey(cekSizeBits int, key interface{}, header map[string]interface{}) (cek []byte, encryptedCek []byte, err error) { if pubKey, ok := key.(*rsa.PublicKey); ok { if cek, err = arrays.Random(cekSizeBits >> 3); err == nil { encryptedCek, err = rsa.EncryptPKCS1v15(rand.Reader, pubKey, cek) return } return nil, nil, err } return nil, nil, errors.New("RsaPkcs1v15.WrapNewKey(): expected key to be '*rsa.PublicKey'") }
// Encrypt the given payload. Based on the key encryption algorithm, // this will either use RSA-PKCS1v1.5 or RSA-OAEP (with SHA-1 or SHA-256). func (ctx rsaEncrypterVerifier) encrypt(cek []byte, alg KeyAlgorithm) ([]byte, error) { switch alg { case RSA1_5: return rsa.EncryptPKCS1v15(randReader, ctx.publicKey, cek) case RSA_OAEP: return rsa.EncryptOAEP(sha1.New(), randReader, ctx.publicKey, cek, []byte{}) case RSA_OAEP_256: return rsa.EncryptOAEP(sha256.New(), randReader, ctx.publicKey, cek, []byte{}) } return nil, ErrUnsupportedAlgorithm }
func writePubKeyMsg(rawConn net.Conn, peerKey *rsa.PublicKey, msg []byte) (err error) { encryptedMsg, err := rsa.EncryptPKCS1v15(rand.Reader, peerKey, msg) if err != nil { return } prefixedMsg := lenPrefix(encryptedMsg) _, err = rawConn.Write(prefixedMsg) return }
func (pld *PreLoginData) GetPwd(password string) string { var n big.Int n.SetString(pld.Pubkey, 16) pk := rsa.PublicKey{&n, 65537} msg := fmt.Sprintf("%d\t%s\n%s", pld.Servertime, pld.Nonce, password) fmt.Println("msg:", msg) code, err := rsa.EncryptPKCS1v15(rand.Reader, &pk, []byte(msg)) if err != nil { panic(err) } hexCode := hex.EncodeToString(code) fmt.Println("code: ", hexCode) return hexCode }
// RSA encrypt func RsaEncrypt(publicKey []byte, origData []byte) ([]byte, error) { 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) k := (pub.N.BitLen() + 7) / 8 if len(origData) > k-11 { o1, e1 := rsa.EncryptPKCS1v15(rand.Reader, pub, origData[:k-19]) o2, e2 := rsa.EncryptPKCS1v15(rand.Reader, pub, origData[k-19:]) if e1 != nil || e2 != nil { return nil, errors.New("RSA encrypt error") } return append(o1, o2...), nil } else { return rsa.EncryptPKCS1v15(rand.Reader, pub, origData) } }
func encryptSessionKey(skey string) { verbose("Encrypting session key...", 2) for recipient, pubkeys := range PUBKEYS { for _, key := range pubkeys { random := rand.Reader ciphertext, err := rsa.EncryptPKCS1v15(random, &key.Key, []byte(skey)) if err != nil { fail(fmt.Sprintf("Unable to encrypt session key for %v-%v: %v\n", recipient, key.Fingerprint, err)) } uuencode(fmt.Sprintf("%v-%v", recipient, key.Fingerprint), ciphertext) } } }