Encrypt implements encrypter. certificate must be a []byte containing the ASN.1 bytes of certificate containing an RSA public key.
(certificate interface{}, plaintext []byte, nonce []byte)
| 30 | // Encrypt implements encrypter. certificate must be a []byte containing the ASN.1 bytes |
| 31 | // of certificate containing an RSA public key. |
| 32 | func (e RSA) Encrypt(certificate interface{}, plaintext []byte, nonce []byte) (*etree.Element, error) { |
| 33 | cert, ok := certificate.(*x509.Certificate) |
| 34 | if !ok { |
| 35 | return nil, ErrIncorrectKeyType("*x.509 certificate") |
| 36 | } |
| 37 | |
| 38 | pubKey, ok := cert.PublicKey.(*rsa.PublicKey) |
| 39 | if !ok { |
| 40 | return nil, ErrIncorrectKeyType("x.509 certificate with an RSA public key") |
| 41 | } |
| 42 | |
| 43 | // generate a key |
| 44 | key := make([]byte, e.BlockCipher.KeySize()) |
| 45 | if _, err := RandReader.Read(key); err != nil { |
| 46 | return nil, err |
| 47 | } |
| 48 | |
| 49 | keyInfoEl := etree.NewElement("ds:KeyInfo") |
| 50 | keyInfoEl.CreateAttr("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#") |
| 51 | |
| 52 | encryptedKey := keyInfoEl.CreateElement("xenc:EncryptedKey") |
| 53 | { |
| 54 | randBuf := make([]byte, 16) |
| 55 | if _, err := RandReader.Read(randBuf); err != nil { |
| 56 | return nil, err |
| 57 | } |
| 58 | encryptedKey.CreateAttr("Id", fmt.Sprintf("_%x", randBuf)) |
| 59 | } |
| 60 | encryptedKey.CreateAttr("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#") |
| 61 | |
| 62 | encryptionMethodEl := encryptedKey.CreateElement("xenc:EncryptionMethod") |
| 63 | encryptionMethodEl.CreateAttr("Algorithm", e.algorithm) |
| 64 | encryptionMethodEl.CreateAttr("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#") |
| 65 | if e.DigestMethod != nil { |
| 66 | dm := encryptionMethodEl.CreateElement("ds:DigestMethod") |
| 67 | dm.CreateAttr("Algorithm", e.DigestMethod.Algorithm()) |
| 68 | dm.CreateAttr("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#") |
| 69 | } |
| 70 | { |
| 71 | innerKeyInfoEl := encryptedKey.CreateElement("ds:KeyInfo") |
| 72 | x509data := innerKeyInfoEl.CreateElement("ds:X509Data") |
| 73 | x509data.CreateElement("ds:X509Certificate").SetText( |
| 74 | base64.StdEncoding.EncodeToString(cert.Raw), |
| 75 | ) |
| 76 | } |
| 77 | |
| 78 | buf, err := e.keyEncrypter(e, pubKey, key) |
| 79 | if err != nil { |
| 80 | return nil, err |
| 81 | } |
| 82 | |
| 83 | cd := encryptedKey.CreateElement("xenc:CipherData") |
| 84 | cd.CreateAttr("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#") |
| 85 | cd.CreateElement("xenc:CipherValue").SetText(base64.StdEncoding.EncodeToString(buf)) |
| 86 | encryptedDataEl, err := e.BlockCipher.Encrypt(key, plaintext, nonce) |
| 87 | if err != nil { |
| 88 | return nil, err |
| 89 | } |
nothing calls this directly
no test coverage detected