private static JweHeader GetHeader() { JweHeader jweHeader = new JweHeader(); jweHeader.Alg = "RSA-OAEP"; jweHeader.Enc = "A128GCM"; jweHeader.Kid = "1"; jweHeader.Zip = "gzip"; return(jweHeader); }
private static string GetEncodeHeader(JweHeader jweHeader) { StringBuffer stringBuffer = new StringBuffer(); string headerJson = stringBuffer.Append("alg=") .Append(jweHeader.Alg) .Append(", enc=") .Append(jweHeader.Enc) .Append(", kid=") .Append(jweHeader.Kid) .Append(", zip=") .Append(jweHeader.Zip) .ToString(); return(Base64.EncodeToString(Encoding.UTF8.GetBytes(headerJson), Base64Flags.UrlSafe | Base64Flags.NoWrap)); }
public static string GenerateJwe(string issuerId, string dataJson) { string jwePrivateKey = Constant.PrivateKey; string sessionKeyPublicKey = Constant.SessionPublicKey; string sessionKey = RandomUtils.GenerateSecureRandomFactor(16); JObject jObject = JObject.Parse(dataJson); jObject.Add("iss", issuerId); // The first part: JWE Head JweHeader jweHeader = GetHeader(); string jweHeaderEncode = GetEncodeHeader(jweHeader); // The Second part: JWE Encrypted Key string encryptedKeyEncode = GetEncryptedKey(sessionKey, sessionKeyPublicKey); // The third part: JWE IV sbyte[] iv = AESUtils.GetIvByte(12); string ivHexStr = new string(HwHex.EncodeHexString(iv)); //Java.Lang.String ivHexString = (Java.Lang.String)ivHexStr; string ivEncode = Base64.EncodeToString(Encoding.UTF8.GetBytes(ivHexStr), Base64Flags.UrlSafe | Base64Flags.NoWrap); // The fourth part: JWE CipherText empty string cipherTextEncode = GetCipherText(jObject.ToString(), sessionKey, iv, jweHeader); // The fifth part: JWE Authentication Tag string authenticationTagEncode = GetAuthenticationTag(jwePrivateKey, sessionKey, jObject.ToString(), jweHeaderEncode, ivEncode); Java.Lang.StringBuilder stringBuilder = new Java.Lang.StringBuilder(); return(stringBuilder.Append(jweHeaderEncode) .Append(".") .Append(encryptedKeyEncode) .Append(".") .Append(ivEncode) .Append(".") .Append(cipherTextEncode) .Append(".") .Append(authenticationTagEncode) .ToString()); }
private static string GetCipherText(string dataJson, string sessionKey, sbyte[] iv, JweHeader jweHeader) { if (!"A128GCM".Equals(jweHeader.Enc)) { System.Console.WriteLine("enc only support A128GCM."); return(""); } if (!"gzip".Equals(jweHeader.Zip)) { System.Console.WriteLine("zip only support gzip."); return(""); } string payLoadEncrypt = AESUtils.EncryptByGcm(dataJson, sessionKey, iv); sbyte[] payLoadEncryptCompressByte = Compress((sbyte[])(Array)Encoding.UTF8.GetBytes(payLoadEncrypt)); string cipherTextEncode = Base64.EncodeToString((byte[])(Array)payLoadEncryptCompressByte, Base64Flags.UrlSafe | Base64Flags.NoWrap); return(cipherTextEncode); }