Created
May 4, 2018 20:59
-
-
Save loic-sharma/e5c6af48e62607a30bd8dfdef4b02bc4 to your computer and use it in GitHub Desktop.
Repository sign a NuGet Package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Security.Cryptography.X509Certificates; | |
using System.Threading.Tasks; | |
using NuGet.Packaging.Signing; | |
namespace ConsoleApp7 | |
{ | |
using System.Threading; | |
using NuGet.Common; | |
using NuGetHashAlrorithmName = NuGet.Common.HashAlgorithmName; | |
public class Program | |
{ | |
static void Main(string[] args) | |
=> MainAsync(args) | |
.GetAwaiter() | |
.GetResult(); | |
static async Task MainAsync(string[] args) | |
{ | |
var signingCertificatePath = "codeSignPackage.pfx"; | |
var packageInputPath = "MyPackage.1.0.0.nupkg"; | |
var packageOutputPath = "MyPackage.Reposigned.1.0.0.nupkg"; | |
var signingCertificate = new X509Certificate2(signingCertificatePath); | |
var signer = new PackageSigner(); | |
var request = new RepositorySignPackageRequest( | |
signingCertificate, | |
NuGetHashAlrorithmName.SHA256, | |
NuGetHashAlrorithmName.SHA256, | |
new Uri("https://example-service/v3/index.json"), | |
new[] { "nuget", "microsoft" }); | |
using (var packageStream = File.OpenRead(packageInputPath)) | |
using (var signedPackageStream = await signer.SignPackageStreamAsync(packageStream, request)) | |
using (var outputStream = File.Create(packageOutputPath)) | |
{ | |
signedPackageStream.Seek(0, SeekOrigin.Begin); | |
signedPackageStream.CopyTo(outputStream); | |
} | |
} | |
} | |
public class PackageSigner | |
{ | |
public const string TimestampServerUriString = "http://sha256timestamp.ws.symantec.com/sha256/timestamp"; | |
public async Task<Stream> SignPackageStreamAsync(Stream packageStream, SignPackageRequest request) | |
{ | |
var timestampUri = new Uri(TimestampServerUriString); | |
var timestampProvider = new Rfc3161TimestampProvider(timestampUri); | |
var signatureProvider = new X509SignatureProvider(timestampProvider); | |
Stream outputPackageStream = null; | |
try | |
{ | |
outputPackageStream = new MemoryStream(); | |
await SigningUtility.SignAsync( | |
new SigningOptions( | |
inputPackageStream: new Lazy<Stream>(() => packageStream), | |
outputPackageStream: new Lazy<Stream>(() => outputPackageStream), | |
overwrite: true, | |
signatureProvider: signatureProvider, | |
logger: new NullLogger()), | |
request, | |
CancellationToken.None); | |
return outputPackageStream; | |
} | |
catch | |
{ | |
outputPackageStream?.Dispose(); | |
throw; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment