-
Notifications
You must be signed in to change notification settings - Fork 2
/
EncryptionDecryptionController.cs
88 lines (72 loc) · 3.34 KB
/
EncryptionDecryptionController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.IO;
using System.Threading.Tasks;
using Azure.Storage.Blobs.Specialized;
using PgpCore;
namespace DecryptPGPFunction
{
public class EncryptionDecryptionController
{
public EncryptionDecryptionRequest Request { get; set; }
public EncryptionDecryptionController(EncryptionDecryptionRequest _request)
{
this.Request = _request;
}
public async Task EncryptAsync()
{
var inputStream = new MemoryStream();
await DownloadFileFromBlobAsync(Request.InputFile, inputStream);
var outputStream = new MemoryStream();
var encryptionKeyStream = new MemoryStream();
await DownloadFileFromBlobAsync(Request.EncryptionDecryptionKeyFile, encryptionKeyStream);
await new PGP().EncryptStreamAsync(inputStream, outputStream, encryptionKeyStream, Request.Armor);
await UploadStreamToBlobAsync(Request.OutputFile, outputStream);
}
public async Task DecryptAsync()
{
var inputStream = new MemoryStream();
await DownloadFileFromBlobAsync(Request.InputFile, inputStream);
var outputStream = new MemoryStream();
var encryptionKeyStream = new MemoryStream();
await DownloadFileFromBlobAsync(Request.EncryptionDecryptionKeyFile, encryptionKeyStream);
await new PGP().DecryptStreamAsync(inputStream, outputStream, encryptionKeyStream, Request.passPhrase);
await UploadStreamToBlobAsync(Request.OutputFile, outputStream);
}
public async Task DownloadFileFromBlobAsync(AzureFileInfo _azureFileInfo, MemoryStream _toStream)
{
try
{
var blobClient = new BlockBlobClient(_azureFileInfo.ConnectionString, _azureFileInfo.BlobContainerName, _azureFileInfo.BlobName);
await blobClient.DownloadToAsync(_toStream);
_toStream.Position = 0;
}
catch (Exception ex)
{
throw new Azure.RequestFailedException(
$"Unable to download file."
+ $" ConnectionString: {_azureFileInfo.ConnectionString},"
+ $" BlobContainerName: {_azureFileInfo.BlobContainerName},"
+ $" BlobName: {_azureFileInfo.BlobName}."
+ $" Exception message: {ex.Message}");
}
}
public async Task UploadStreamToBlobAsync(AzureFileInfo _azureFileInfo, MemoryStream _stream)
{
try
{
_stream.Position = 0;
var blobClient = new BlockBlobClient(_azureFileInfo.ConnectionString, _azureFileInfo.BlobContainerName, _azureFileInfo.BlobName);
await blobClient.UploadAsync(_stream);
}
catch (Exception ex)
{
throw new Azure.RequestFailedException(
$"Unable to upload file."
+ $" ConnectionString: {_azureFileInfo.ConnectionString},"
+ $" BlobContainerName: {_azureFileInfo.BlobContainerName},"
+ $" BlobName: {_azureFileInfo.BlobName}."
+ $" Exception message: {ex.Message}");
}
}
}
}