沃梦达 / 编程问答 / php问题 / 正文

如何在 .net 中登录 url 以进行谷歌云存储

How to sign url in .net for google cloud storage(如何在 .net 中登录 url 以进行谷歌云存储)

本文介绍了如何在 .net 中登录 url 以进行谷歌云存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I want to know that how to generate signurl using google cloud storage classes in .net

I have created string as per the requirement

GET


1388534400
/bucket/objectname

but I now want to sign this url with p12 key and then want to make it url friendly

This library doesn't show specific function for it -> https://developers.google.com/resources/api-libraries/documentation/storage/v1/csharp/latest/annotated.html

So, basically I need .net alternate of Google_Signer_P12 class of php

$signer = new Google_Signer_P12(file_get_contents(__DIR__.'/'."final.p12"), "notasecret");
$signature = $signer->sign($to_sign);

解决方案

This is my google signer code, One can make it more dynamic as per their needs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

using System.Web;
using System.Security.Cryptography.X509Certificates;

namespace HHAFSGoogle
{
    static class GoogleSigner
    {
        private static string hashAlgo = "SHA256";
        public static string ServiceAccountEmail
        {
            get
            {
                return "XXXXXXXXXXXXX-YYYYYYYYYYYYYYYYYYYYYYYY@developer.gserviceaccount.com";
            }
        }

        public static string GoogleSecreat
        {
            get
            {
                return "notasecret";
            }
        }

        public static string GoogleBucketDir
        {
            get
            {
                return "MyBucketDirectory";
            }
        }

        public static string GoogleBucketName
        {
            get
            {
                return "MyBucket";
            }
        }

        public static string CertiFilelocation
        {
            get
            {
                return System.Web.HttpContext.Current.Server.MapPath("p12file.p12");
            }
        }

        /// <summary>
        /// Get URL signature
        /// </summary>
        /// <param name="base64EncryptedData"></param>
        /// <param name="certiFilelocation"></param>
        /// <returns></returns>
        public static string GetSignature(string base64EncryptedData, string certiFilelocation)
        {
            X509Certificate2 certificate = new X509Certificate2(certiFilelocation, GoogleSecreat, X509KeyStorageFlags.Exportable);

            RSACryptoServiceProvider csp = (RSACryptoServiceProvider)certificate.PrivateKey;

            RSACryptoServiceProvider privateKey1 = new RSACryptoServiceProvider();
            privateKey1.ImportParameters(csp.ExportParameters(true));

            csp.ImportParameters(privateKey1.ExportParameters(true));

            byte[] data = Encoding.UTF8.GetBytes(base64EncryptedData.Replace("
", ""));

            byte[] signature = privateKey1.SignData(data, hashAlgo);

            bool isValid = privateKey1.VerifyData(data, hashAlgo, signature);

            if (isValid)
            {
                return Convert.ToBase64String(signature);
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Get signed URL by Signature
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="method"></param>
        /// <param name="content_type"></param>
        /// <param name="duration"></param>
        /// <returns></returns>
        public static string GetSignedURL(string fileName, string method = "GET", string content_type = "", int duration = 10)
        {
            TimeSpan span = (DateTime.UtcNow.AddMinutes(10) - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            var expires = Math.Round(span.TotalSeconds, 0);

            // Encode filename, so URL characters like %20 for space could be handled properly in signature
            fileName = HttpUtility.UrlPathEncode(fileName);

            // Generate a string to sign
            StringBuilder sbFileParam = new StringBuilder();
            sbFileParam.AppendLine(method);  //Could be GET, PUT, DELETE, POST
            //  /* Content-MD5 */ "
" .
            sbFileParam.AppendLine();
            sbFileParam.AppendLine(content_type);   // Type of content you would upload e.g. image/jpeg
            sbFileParam.AppendLine(expires.ToString());     // Time when link should expire and shouldn't work longer
            sbFileParam.Append("/" + GoogleBucketName + "/" + fileName);

            var signature = System.Web.HttpContext.Current.Server.UrlEncode(GetSignature(sbFileParam.ToString(), CertiFilelocation));

            return ("https://storage.googleapis.com/MyBucket/" + fileName +
                        "?response-content-disposition=attachment;&GoogleAccessId=" + ServiceAccountEmail +
                        "&Expires=" + expires + "&Signature=" + signature);
        }
    }
}

and to download file call above class to get signed url

GoogleSigner.GetSignedURL(bucketFileName)

and to upload file call above class to get signed url for upload url

GoogleSigner.GetSignedURL(fileName, "PUT", type);

这篇关于如何在 .net 中登录 url 以进行谷歌云存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 .net 中登录 url 以进行谷歌云存储

基础教程推荐