| 1 | package pkcs7 |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto" |
| 6 | "crypto/aes" |
| 7 | "crypto/cipher" |
| 8 | "crypto/des" |
| 9 | "crypto/rand" |
| 10 | "crypto/rsa" |
| 11 | "crypto/x509" |
| 12 | "crypto/x509/pkix" |
| 13 | "encoding/asn1" |
| 14 | "errors" |
| 15 | "fmt" |
| 16 | ) |
| 17 | |
| 18 | type envelopedData struct { |
| 19 | Version int |
| 20 | RecipientInfos []recipientInfo `asn1:"set"` |
| 21 | EncryptedContentInfo encryptedContentInfo |
| 22 | } |
| 23 | |
| 24 | type encryptedData struct { |
| 25 | Version int |
| 26 | EncryptedContentInfo encryptedContentInfo |
| 27 | } |
| 28 | |
| 29 | type recipientInfo struct { |
| 30 | Version int |
| 31 | IssuerAndSerialNumber issuerAndSerial |
| 32 | KeyEncryptionAlgorithm pkix.AlgorithmIdentifier |
| 33 | EncryptedKey []byte |
| 34 | } |
| 35 | |
| 36 | type encryptedContentInfo struct { |
| 37 | ContentType asn1.ObjectIdentifier |
| 38 | ContentEncryptionAlgorithm pkix.AlgorithmIdentifier |
| 39 | EncryptedContent asn1.RawValue `asn1:"tag:0,optional"` |
| 40 | } |
| 41 | |
| 42 | const ( |
| 43 | // EncryptionAlgorithmDESCBC is the DES CBC encryption algorithm |
| 44 | EncryptionAlgorithmDESCBC = iota |
| 45 | |
| 46 | // EncryptionAlgorithmAES128CBC is the AES 128 bits with CBC encryption algorithm |
| 47 | // Avoid this algorithm unless required for interoperability; use AES GCM instead. |
| 48 | EncryptionAlgorithmAES128CBC |
| 49 | |
| 50 | // EncryptionAlgorithmAES256CBC is the AES 256 bits with CBC encryption algorithm |
| 51 | // Avoid this algorithm unless required for interoperability; use AES GCM instead. |
| 52 | EncryptionAlgorithmAES256CBC |
| 53 | |
| 54 | // EncryptionAlgorithmAES128GCM is the AES 128 bits with GCM encryption algorithm |
| 55 | EncryptionAlgorithmAES128GCM |
| 56 | |
| 57 | // EncryptionAlgorithmAES256GCM is the AES 256 bits with GCM encryption algorithm |
| 58 | EncryptionAlgorithmAES256GCM |
| 59 | ) |
| 60 | |
| 61 | // ContentEncryptionAlgorithm determines the algorithm used to encrypt the |
| 62 | // plaintext message. Change the value of this variable to change which |
| 63 | // algorithm is used in the Encrypt() function. |
| 64 | var ContentEncryptionAlgorithm = EncryptionAlgorithmDESCBC |
| 65 | |
| 66 | // ErrUnsupportedEncryptionAlgorithm is returned when attempting to encrypt |
| 67 | // content with an unsupported algorithm. |
| 68 | var ErrUnsupportedEncryptionAlgorithm = errors.New("pkcs7: cannot encrypt content: only DES-CBC, AES-CBC, and AES-GCM supported") |
| 69 | |
| 70 | // KeyEncryptionAlgorithm determines the algorithm used to encrypt a |
| 71 | // content key. Change the value of this variable to change which |
| 72 | // algorithm is used in the Encrypt() function. |
| 73 | var KeyEncryptionAlgorithm = OIDEncryptionAlgorithmRSA |
| 74 | |
| 75 | // ErrUnsupportedKeyEncryptionAlgorithm is returned when an |
| 76 | // unsupported key encryption algorithm OID is provided. |
| 77 | var ErrUnsupportedKeyEncryptionAlgorithm = errors.New("pkcs7: unsupported key encryption algorithm provided") |
| 78 | |
| 79 | // KeyEncryptionHash determines the crypto.Hash algorithm to use |
| 80 | // when encrypting a content key. Change the value of this variable |
| 81 | // to change which algorithm is used in the Encrypt() function. |
| 82 | var KeyEncryptionHash = crypto.SHA256 |
| 83 | |
| 84 | // ErrUnsupportedKeyEncryptionHash is returned when an |
| 85 | // unsupported key encryption hash is provided. |
| 86 | var ErrUnsupportedKeyEncryptionHash = errors.New("pkcs7: unsupported key encryption hash provided") |
| 87 | |
| 88 | // ErrPSKNotProvided is returned when attempting to encrypt |
| 89 | // using a PSK without actually providing the PSK. |
| 90 | var ErrPSKNotProvided = errors.New("pkcs7: cannot encrypt content: PSK not provided") |
| 91 | |
| 92 | const nonceSize = 12 |
| 93 | |
| 94 | type aesGCMParameters struct { |
| 95 | Nonce []byte `asn1:"tag:4"` |
| 96 | ICVLen int |
| 97 | } |
| 98 | |
| 99 | func encryptAESGCM(content []byte, key []byte) ([]byte, *encryptedContentInfo, error) { |
| 100 | var keyLen int |
| 101 | var algID asn1.ObjectIdentifier |
| 102 | switch ContentEncryptionAlgorithm { |
| 103 | case EncryptionAlgorithmAES128GCM: |
| 104 | keyLen = 16 |
| 105 | algID = OIDEncryptionAlgorithmAES128GCM |
| 106 | case EncryptionAlgorithmAES256GCM: |
| 107 | keyLen = 32 |
| 108 | algID = OIDEncryptionAlgorithmAES256GCM |
| 109 | default: |
| 110 | return nil, nil, fmt.Errorf("invalid ContentEncryptionAlgorithm in encryptAESGCM: %d", ContentEncryptionAlgorithm) |
| 111 | } |
| 112 | if key == nil { |
| 113 | // Create AES key |
| 114 | key = make([]byte, keyLen) |
| 115 | |
| 116 | _, err := rand.Read(key) |
| 117 | if err != nil { |
| 118 | return nil, nil, err |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | // Create nonce |
| 123 | nonce := make([]byte, nonceSize) |
| 124 | |
| 125 | _, err := rand.Read(nonce) |
| 126 | if err != nil { |
| 127 | return nil, nil, err |
| 128 | } |
| 129 | |
| 130 | // Encrypt content |
| 131 | block, err := aes.NewCipher(key) |
| 132 | if err != nil { |
| 133 | return nil, nil, err |
| 134 | } |
| 135 | |
| 136 | gcm, err := cipher.NewGCM(block) |
| 137 | if err != nil { |
| 138 | return nil, nil, err |
| 139 | } |
| 140 | |
| 141 | ciphertext := gcm.Seal(nil, nonce, content, nil) |
| 142 | |
| 143 | // Prepare ASN.1 Encrypted Content Info |
| 144 | paramSeq := aesGCMParameters{ |
| 145 | Nonce: nonce, |
| 146 | ICVLen: gcm.Overhead(), |
| 147 | } |
| 148 | |
| 149 | paramBytes, err := asn1.Marshal(paramSeq) |
| 150 | if err != nil { |
| 151 | return nil, nil, err |
| 152 | } |
| 153 | |
| 154 | eci := encryptedContentInfo{ |
| 155 | ContentType: OIDData, |
| 156 | ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{ |
| 157 | Algorithm: algID, |
| 158 | Parameters: asn1.RawValue{ |
| 159 | Tag: asn1.TagSequence, |
| 160 | Bytes: paramBytes, |
| 161 | }, |
| 162 | }, |
| 163 | EncryptedContent: marshalEncryptedContent(ciphertext), |
| 164 | } |
| 165 | |
| 166 | return key, &eci, nil |
| 167 | } |
| 168 | |
| 169 | func encryptDESCBC(content []byte, key []byte) ([]byte, *encryptedContentInfo, error) { |
| 170 | if key == nil { |
| 171 | // Create DES key |
| 172 | key = make([]byte, 8) |
| 173 | |
| 174 | _, err := rand.Read(key) |
| 175 | if err != nil { |
| 176 | return nil, nil, err |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | // Create CBC IV |
| 181 | iv := make([]byte, des.BlockSize) |
| 182 | _, err := rand.Read(iv) |
| 183 | if err != nil { |
| 184 | return nil, nil, err |
| 185 | } |
| 186 | |
| 187 | // Encrypt padded content |
| 188 | block, err := des.NewCipher(key) |
| 189 | if err != nil { |
| 190 | return nil, nil, err |
| 191 | } |
| 192 | mode := cipher.NewCBCEncrypter(block, iv) |
| 193 | plaintext, err := pad(content, mode.BlockSize()) |
| 194 | if err != nil { |
| 195 | return nil, nil, err |
| 196 | } |
| 197 | cyphertext := make([]byte, len(plaintext)) |
| 198 | mode.CryptBlocks(cyphertext, plaintext) |
| 199 | |
| 200 | // Prepare ASN.1 Encrypted Content Info |
| 201 | eci := encryptedContentInfo{ |
| 202 | ContentType: OIDData, |
| 203 | ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{ |
| 204 | Algorithm: OIDEncryptionAlgorithmDESCBC, |
| 205 | Parameters: asn1.RawValue{Tag: 4, Bytes: iv}, |
| 206 | }, |
| 207 | EncryptedContent: marshalEncryptedContent(cyphertext), |
| 208 | } |
| 209 | |
| 210 | return key, &eci, nil |
| 211 | } |
| 212 | |
| 213 | func encryptAESCBC(content []byte, key []byte) ([]byte, *encryptedContentInfo, error) { |
| 214 | var keyLen int |
| 215 | var algID asn1.ObjectIdentifier |
| 216 | switch ContentEncryptionAlgorithm { |
| 217 | case EncryptionAlgorithmAES128CBC: |
| 218 | keyLen = 16 |
| 219 | algID = OIDEncryptionAlgorithmAES128CBC |
| 220 | case EncryptionAlgorithmAES256CBC: |
| 221 | keyLen = 32 |
| 222 | algID = OIDEncryptionAlgorithmAES256CBC |
| 223 | default: |
| 224 | return nil, nil, fmt.Errorf("invalid ContentEncryptionAlgorithm in encryptAESCBC: %d", ContentEncryptionAlgorithm) |
| 225 | } |
| 226 | |
| 227 | if key == nil { |
| 228 | // Create AES key |
| 229 | key = make([]byte, keyLen) |
| 230 | |
| 231 | _, err := rand.Read(key) |
| 232 | if err != nil { |
| 233 | return nil, nil, err |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | // Create CBC IV |
| 238 | iv := make([]byte, aes.BlockSize) |
| 239 | _, err := rand.Read(iv) |
| 240 | if err != nil { |
| 241 | return nil, nil, err |
| 242 | } |
| 243 | |
| 244 | // Encrypt padded content |
| 245 | block, err := aes.NewCipher(key) |
| 246 | if err != nil { |
| 247 | return nil, nil, err |
| 248 | } |
| 249 | mode := cipher.NewCBCEncrypter(block, iv) |
| 250 | plaintext, err := pad(content, mode.BlockSize()) |
| 251 | if err != nil { |
| 252 | return nil, nil, err |
| 253 | } |
| 254 | cyphertext := make([]byte, len(plaintext)) |
| 255 | mode.CryptBlocks(cyphertext, plaintext) |
| 256 | |
| 257 | // Prepare ASN.1 Encrypted Content Info |
| 258 | eci := encryptedContentInfo{ |
| 259 | ContentType: OIDData, |
| 260 | ContentEncryptionAlgorithm: pkix.AlgorithmIdentifier{ |
| 261 | Algorithm: algID, |
| 262 | Parameters: asn1.RawValue{Tag: 4, Bytes: iv}, |
| 263 | }, |
| 264 | EncryptedContent: marshalEncryptedContent(cyphertext), |
| 265 | } |
| 266 | |
| 267 | return key, &eci, nil |
| 268 | } |
| 269 | |
| 270 | // Encrypt creates and returns an envelope data PKCS7 structure with encrypted |
| 271 | // recipient keys for each recipient public key. |
| 272 | // |
| 273 | // The algorithm used to perform encryption is determined by the current value |
| 274 | // of the global ContentEncryptionAlgorithm package variable. By default, the |
| 275 | // value is EncryptionAlgorithmDESCBC. To use a different algorithm, change the |
| 276 | // value before calling Encrypt(). For example: |
| 277 | // |
| 278 | // ContentEncryptionAlgorithm = EncryptionAlgorithmAES256GCM |
| 279 | // |
| 280 | // TODO(fullsailor): Add support for encrypting content with other algorithms |
| 281 | func Encrypt(content []byte, recipients []*x509.Certificate) ([]byte, error) { |
| 282 | var eci *encryptedContentInfo |
| 283 | var key []byte |
| 284 | var err error |
| 285 | |
| 286 | // Apply chosen symmetric encryption method |
| 287 | switch ContentEncryptionAlgorithm { |
| 288 | case EncryptionAlgorithmDESCBC: |
| 289 | key, eci, err = encryptDESCBC(content, nil) |
| 290 | case EncryptionAlgorithmAES128CBC: |
| 291 | fallthrough |
| 292 | case EncryptionAlgorithmAES256CBC: |
| 293 | key, eci, err = encryptAESCBC(content, nil) |
| 294 | case EncryptionAlgorithmAES128GCM: |
| 295 | fallthrough |
| 296 | case EncryptionAlgorithmAES256GCM: |
| 297 | key, eci, err = encryptAESGCM(content, nil) |
| 298 | |
| 299 | default: |
| 300 | return nil, ErrUnsupportedEncryptionAlgorithm |
| 301 | } |
| 302 | |
| 303 | if err != nil { |
| 304 | return nil, err |
| 305 | } |
| 306 | |
| 307 | // Prepare each recipient's encrypted cipher key |
| 308 | recipientInfos := make([]recipientInfo, len(recipients)) |
| 309 | for i, recipient := range recipients { |
| 310 | algorithm := KeyEncryptionAlgorithm |
| 311 | hash := KeyEncryptionHash |
| 312 | var kea pkix.AlgorithmIdentifier |
| 313 | switch { |
| 314 | case algorithm.Equal(OIDEncryptionAlgorithmRSAESOAEP): |
| 315 | parameters, err := getParametersForKeyEncryptionAlgorithm(algorithm, hash) |
| 316 | if err != nil { |
| 317 | return nil, fmt.Errorf("failed to get parameters for key encryption: %v", err) |
| 318 | } |
| 319 | kea = pkix.AlgorithmIdentifier{ |
| 320 | Algorithm: algorithm, |
| 321 | Parameters: parameters, |
| 322 | } |
| 323 | case algorithm.Equal(OIDEncryptionAlgorithmRSA): |
| 324 | kea = pkix.AlgorithmIdentifier{ |
| 325 | Algorithm: algorithm, |
| 326 | } |
| 327 | default: |
| 328 | return nil, ErrUnsupportedKeyEncryptionAlgorithm |
| 329 | } |
| 330 | encrypted, err := encryptKey(key, recipient, algorithm, hash) |
| 331 | if err != nil { |
| 332 | return nil, err |
| 333 | } |
| 334 | ias, err := cert2issuerAndSerial(recipient) |
| 335 | if err != nil { |
| 336 | return nil, err |
| 337 | } |
| 338 | info := recipientInfo{ |
| 339 | Version: 0, |
| 340 | IssuerAndSerialNumber: ias, |
| 341 | KeyEncryptionAlgorithm: kea, |
| 342 | EncryptedKey: encrypted, |
| 343 | } |
| 344 | recipientInfos[i] = info |
| 345 | } |
| 346 | |
| 347 | // Prepare envelope content |
| 348 | envelope := envelopedData{ |
| 349 | EncryptedContentInfo: *eci, |
| 350 | Version: 0, |
| 351 | RecipientInfos: recipientInfos, |
| 352 | } |
| 353 | innerContent, err := asn1.Marshal(envelope) |
| 354 | if err != nil { |
| 355 | return nil, err |
| 356 | } |
| 357 | |
| 358 | // Prepare outer payload structure |
| 359 | wrapper := contentInfo{ |
| 360 | ContentType: OIDEnvelopedData, |
| 361 | Content: asn1.RawValue{Class: 2, Tag: 0, IsCompound: true, Bytes: innerContent}, |
| 362 | } |
| 363 | |
| 364 | return asn1.Marshal(wrapper) |
| 365 | } |
| 366 | |
| 367 | func getParametersForKeyEncryptionAlgorithm(algorithm asn1.ObjectIdentifier, hash crypto.Hash) (asn1.RawValue, error) { |
| 368 | if !algorithm.Equal(OIDEncryptionAlgorithmRSAESOAEP) { |
| 369 | return asn1.RawValue{}, nil // return empty; not used |
| 370 | } |
| 371 | |
| 372 | params := rsaOAEPAlgorithmParameters{} |
| 373 | switch hash { |
| 374 | case crypto.SHA1: |
| 375 | params.HashFunc = pkix.AlgorithmIdentifier{Algorithm: OIDDigestAlgorithmSHA1} |
| 376 | case crypto.SHA224: |
| 377 | params.HashFunc = pkix.AlgorithmIdentifier{Algorithm: OIDDigestAlgorithmSHA224} |
| 378 | case crypto.SHA256: |
| 379 | params.HashFunc = pkix.AlgorithmIdentifier{Algorithm: OIDDigestAlgorithmSHA256} |
| 380 | case crypto.SHA384: |
| 381 | params.HashFunc = pkix.AlgorithmIdentifier{Algorithm: OIDDigestAlgorithmSHA384} |
| 382 | case crypto.SHA512: |
| 383 | params.HashFunc = pkix.AlgorithmIdentifier{Algorithm: OIDDigestAlgorithmSHA512} |
| 384 | default: |
| 385 | return asn1.RawValue{}, ErrUnsupportedAlgorithm |
| 386 | } |
| 387 | |
| 388 | b, err := asn1.Marshal(params) |
| 389 | if err != nil { |
| 390 | return asn1.RawValue{}, fmt.Errorf("failed marshaling key encryption parameters: %v", err) |
| 391 | } |
| 392 | |
| 393 | return asn1.RawValue{ |
| 394 | FullBytes: b, |
| 395 | }, nil |
| 396 | } |
| 397 | |
| 398 | // EncryptUsingPSK creates and returns an encrypted data PKCS7 structure, |
| 399 | // encrypted using caller provided pre-shared secret. |
| 400 | func EncryptUsingPSK(content []byte, key []byte) ([]byte, error) { |
| 401 | var eci *encryptedContentInfo |
| 402 | var err error |
| 403 | |
| 404 | if key == nil { |
| 405 | return nil, ErrPSKNotProvided |
| 406 | } |
| 407 | |
| 408 | // Apply chosen symmetric encryption method |
| 409 | switch ContentEncryptionAlgorithm { |
| 410 | case EncryptionAlgorithmDESCBC: |
| 411 | _, eci, err = encryptDESCBC(content, key) |
| 412 | |
| 413 | case EncryptionAlgorithmAES128GCM: |
| 414 | fallthrough |
| 415 | case EncryptionAlgorithmAES256GCM: |
| 416 | _, eci, err = encryptAESGCM(content, key) |
| 417 | |
| 418 | default: |
| 419 | return nil, ErrUnsupportedEncryptionAlgorithm |
| 420 | } |
| 421 | |
| 422 | if err != nil { |
| 423 | return nil, err |
| 424 | } |
| 425 | |
| 426 | // Prepare encrypted-data content |
| 427 | ed := encryptedData{ |
| 428 | Version: 0, |
| 429 | EncryptedContentInfo: *eci, |
| 430 | } |
| 431 | innerContent, err := asn1.Marshal(ed) |
| 432 | if err != nil { |
| 433 | return nil, err |
| 434 | } |
| 435 | |
| 436 | // Prepare outer payload structure |
| 437 | wrapper := contentInfo{ |
| 438 | ContentType: OIDEncryptedData, |
| 439 | Content: asn1.RawValue{Class: 2, Tag: 0, IsCompound: true, Bytes: innerContent}, |
| 440 | } |
| 441 | |
| 442 | return asn1.Marshal(wrapper) |
| 443 | } |
| 444 | |
| 445 | func marshalEncryptedContent(content []byte) asn1.RawValue { |
| 446 | return asn1.RawValue{Bytes: content, Class: 2, IsCompound: false} |
| 447 | } |
| 448 | |
| 449 | func encryptKey(key []byte, recipient *x509.Certificate, algorithm asn1.ObjectIdentifier, hash crypto.Hash) ([]byte, error) { |
| 450 | pub, ok := recipient.PublicKey.(*rsa.PublicKey) |
| 451 | if !ok { |
| 452 | return nil, ErrUnsupportedKeyType |
| 453 | } |
| 454 | |
| 455 | switch { |
| 456 | case algorithm.Equal(OIDEncryptionAlgorithmRSA): |
| 457 | return rsa.EncryptPKCS1v15(rand.Reader, pub, key) |
| 458 | case algorithm.Equal(OIDEncryptionAlgorithmRSAESOAEP): |
| 459 | return rsa.EncryptOAEP(hash.New(), rand.Reader, pub, key, nil) |
| 460 | default: |
| 461 | return nil, ErrUnsupportedKeyEncryptionAlgorithm |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | func pad(data []byte, blocklen int) ([]byte, error) { |
| 466 | if blocklen < 1 { |
| 467 | return nil, fmt.Errorf("invalid blocklen %d", blocklen) |
| 468 | } |
| 469 | padlen := blocklen - (len(data) % blocklen) |
| 470 | if padlen == 0 { |
| 471 | padlen = blocklen |
| 472 | } |
| 473 | pad := bytes.Repeat([]byte{byte(padlen)}, padlen) |
| 474 | return append(data, pad...), nil |
| 475 | } |