Encrypt encrypts plaintext with key, which should be a []byte of length KeySize(). It returns an xenc:EncryptedData element.
(key interface{}, plaintext []byte, _ []byte)
| 33 | // Encrypt encrypts plaintext with key, which should be a []byte of length KeySize(). |
| 34 | // It returns an xenc:EncryptedData element. |
| 35 | func (e CBC) Encrypt(key interface{}, plaintext []byte, _ []byte) (*etree.Element, error) { |
| 36 | keyBuf, ok := key.([]byte) |
| 37 | if !ok { |
| 38 | return nil, ErrIncorrectKeyType("[]byte") |
| 39 | } |
| 40 | if len(keyBuf) != e.keySize { |
| 41 | return nil, ErrIncorrectKeyLength(e.keySize) |
| 42 | } |
| 43 | |
| 44 | block, err := e.cipher(keyBuf) |
| 45 | if err != nil { |
| 46 | return nil, err |
| 47 | } |
| 48 | |
| 49 | encryptedDataEl := etree.NewElement("xenc:EncryptedData") |
| 50 | encryptedDataEl.CreateAttr("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#") |
| 51 | { |
| 52 | randBuf := make([]byte, 16) |
| 53 | if _, err := io.ReadFull(RandReader, randBuf); err != nil { |
| 54 | return nil, err |
| 55 | } |
| 56 | encryptedDataEl.CreateAttr("Id", fmt.Sprintf("_%x", randBuf)) |
| 57 | } |
| 58 | |
| 59 | em := encryptedDataEl.CreateElement("xenc:EncryptionMethod") |
| 60 | em.CreateAttr("Algorithm", e.algorithm) |
| 61 | em.CreateAttr("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#") |
| 62 | |
| 63 | plaintext = appendPadding(plaintext, block.BlockSize()) |
| 64 | |
| 65 | iv := make([]byte, block.BlockSize(), block.BlockSize()+len(plaintext)) |
| 66 | if _, err := io.ReadFull(RandReader, iv); err != nil { |
| 67 | return nil, err |
| 68 | } |
| 69 | |
| 70 | mode := cipher.NewCBCEncrypter(block, iv) |
| 71 | ciphertext := make([]byte, len(plaintext)) |
| 72 | mode.CryptBlocks(ciphertext, plaintext) |
| 73 | ciphertext = append(iv, ciphertext...) |
| 74 | |
| 75 | cd := encryptedDataEl.CreateElement("xenc:CipherData") |
| 76 | cd.CreateAttr("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#") |
| 77 | cd.CreateElement("xenc:CipherValue").SetText(base64.StdEncoding.EncodeToString(ciphertext)) |
| 78 | return encryptedDataEl, nil |
| 79 | } |
| 80 | |
| 81 | // Decrypt decrypts an encrypted element with key. If the ciphertext contains an |
| 82 | // EncryptedKey element, then the type of `key` is determined by the registered |