|
| 1 | +// Copyright The Notary Project Authors. |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +package utils |
| 15 | + |
| 16 | +import ( |
| 17 | + "crypto/aes" |
| 18 | + "crypto/cipher" |
| 19 | + "fmt" |
| 20 | + "os" |
| 21 | +) |
| 22 | + |
| 23 | +// DecryptFile decrypts the AES encrypted file using an AES key and outputs the |
| 24 | +// decrypted file. |
| 25 | +func DecryptFile(inputFilename string, aesKey []byte, outputFilename string) error { |
| 26 | + ciphertext, err := os.ReadFile(inputFilename) |
| 27 | + if err != nil { |
| 28 | + return err |
| 29 | + } |
| 30 | + |
| 31 | + block, err := aes.NewCipher(aesKey) |
| 32 | + if err != nil { |
| 33 | + return err |
| 34 | + } |
| 35 | + |
| 36 | + aesGCM, err := cipher.NewGCM(block) |
| 37 | + if err != nil { |
| 38 | + return err |
| 39 | + } |
| 40 | + |
| 41 | + nonceSize := aesGCM.NonceSize() |
| 42 | + if len(ciphertext) < nonceSize { |
| 43 | + return fmt.Errorf("ciphertext too short") |
| 44 | + } |
| 45 | + |
| 46 | + nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:] |
| 47 | + |
| 48 | + plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil) |
| 49 | + if err != nil { |
| 50 | + return err |
| 51 | + } |
| 52 | + |
| 53 | + return os.WriteFile(outputFilename, plaintext, 0600) |
| 54 | +} |
0 commit comments