none
Java to C# RRS feed

  • Question

  • Hello,  I have some Java code that I'm trying to write in c#.

    Here is the Java snippet:

    byte[] keyBytes = key.getBytes();
            SecretKey originalKey = new SecretKeySpec(keyBytes, 0, keyBytes.length, "AES");
            JWEHeader jweHeader = new JWEHeader(JWEAlgorithm.A256GCMKW, EncryptionMethod.A256GCM);
            Payload payload = new Payload(plainText);
            JWEObject jweObject = new JWEObject(jweHeader, payload);
    jweObject.encrypt(new AESEncrypter(originalKey));
             string jweString = jweObject.serialize();

    Here is what I have so far:

    System.Text.UTF8Encoding utf8 = new UTF8Encoding();
                AesManaged tdes = new AesManaged();
                tdes.Key = utf8.GetBytes(key);
                tdes.Mode = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;

    I'd appreciate any assistance.

    Thank you!




    • Edited by Hiline1961 Friday, May 3, 2019 8:15 PM
    Friday, May 3, 2019 7:51 PM

Answers

All replies

  • The .NET framework has a built-in ability to create JWE objects.

    https://www.scottbrady91.com/C-Sharp/JSON-Web-Encryption-JWE-in-dotnet-Core


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Saturday, May 4, 2019 12:06 AM
  • Thank you for the reply, Tim.  The article was definitely informative.

    I did find a code snippet that I think is close to the Java snippet but I keep getting a bad request error:

    private const int _ivSize = 12;
            private const int _tagSize = 128;
            public string Encrypt(string  encryptionKey, string cardNumber)
            {
                byte[] key = Encoding.UTF8.GetBytes(encryptionKey);
                byte[] card = Encoding.UTF8.GetBytes(cardNumber);

                var iv = this.GenerateIV();

                using (var authAesCng = new AuthenticatedAesCng())
                {
                    authAesCng.CngMode = CngChainingMode.Gcm;

                    authAesCng.Key = key;
                    authAesCng.IV = iv;

                    authAesCng.TagSize = _tagSize;
                    
                    using (var stream = new MemoryStream())
                    using (var encryptor = authAesCng.CreateAuthenticatedEncryptor())
                    using (var cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(card, 0, card.Length);
                        cryptoStream.FlushFinalBlock();
                        var cipherText = stream.ToArray();
                        var encrypted = new byte[cipherText.Length + _ivSize + _tagSize];
                        iv.CopyTo(encrypted, 0);
                        authAesCng.Tag.CopyTo(encrypted, _ivSize);
                        cipherText.CopyTo(encrypted, _ivSize + _tagSize);
                        return Encoding.UTF8.GetString(cipherText);
                    }
                }
            }

            private byte[] GenerateIV()
            {
                var buffer = new byte[_ivSize];
                using (var rng = new RNGCryptoServiceProvider())
                {
                    rng.GetNonZeroBytes(buffer);
                }

                return buffer;
            }


    • Edited by Hiline1961 Monday, May 6, 2019 7:23 PM
    Monday, May 6, 2019 7:09 PM
  • Thank you for the reply, Tim.  The article was definitely informative.

    I did find a code snippet that I think is close to the Java snippet but I keep getting a bad request error:

    private const int _ivSize = 12;
            private const int _tagSize = 128;
            public string Encrypt(string  encryptionKey, string cardNumber)
            {
                byte[] key = Encoding.UTF8.GetBytes(encryptionKey);
                byte[] card = Encoding.UTF8.GetBytes(cardNumber);

                var iv = this.GenerateIV();

                using (var authAesCng = new AuthenticatedAesCng())
                {
                    authAesCng.CngMode = CngChainingMode.Gcm;

                    authAesCng.Key = key;
                    authAesCng.IV = iv;

                    authAesCng.TagSize = _tagSize;
                    
                    using (var stream = new MemoryStream())
                    using (var encryptor = authAesCng.CreateAuthenticatedEncryptor())
                    using (var cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(card, 0, card.Length);
                        cryptoStream.FlushFinalBlock();
                        var cipherText = stream.ToArray();
                        var encrypted = new byte[cipherText.Length + _ivSize + _tagSize];
                        iv.CopyTo(encrypted, 0);
                        authAesCng.Tag.CopyTo(encrypted, _ivSize);
                        cipherText.CopyTo(encrypted, _ivSize + _tagSize);
                        return Encoding.UTF8.GetString(cipherText);
                    }
                }
            }

            private byte[] GenerateIV()
            {
                var buffer = new byte[_ivSize];
                using (var rng = new RNGCryptoServiceProvider())
                {
                    rng.GetNonZeroBytes(buffer);
                }

                return buffer;
            }


                                    

    Hi    Hiline1961,

    Thank you for posting here.

    According to your question, you need to install the Nutget package: Security.Cryptography 1.7.2

    The following are the steps:

    1. Copy the statement.

    Install-Package Security.Cryptography -Version 1.7.2

    2. Open Package Manager Console in Visual Studio (Tools ->Nuget  Package Manager -> Package Manager Console) and install the package

    3. UsingSecurity.Cryptography.

    Then the program will not have compile errors.

    Besides, when you get a exception:

       

    You can try the following code to generate a effective  key:

            private byte[] GenerateKey()
            {
                using (var aes = new AuthenticatedAesCng())
                {
                    aes.CngMode = CngChainingMode.Gcm;
                    aes.GenerateKey();
                    return aes.Key;
                }
            }

    Besides, It would be appreciated if you could close the thread by marking helpful posts as an answer. This will help other members to find the solution quickly if they have faced the similar issue. If you have a new question you can start a new thread  with all necessary code snippets for anyone else to be able to reproduce your issue from scratch along with a detailed description about the results including any exception messages.

    Best Regards

    Yong Lu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, May 7, 2019 6:37 AM
    Moderator
  • Hello!   Here is the solution I used.  It works great.

    https://www.example-code.com/csharp/jwe_A256GCMKW.asp

    I didn't use the kid or tag.  I only used the alg and enc.

    Chilkat.JsonObject jweProtHdr = new Chilkat.JsonObject();
    jweProtHdr.AppendString("alg","A256GCMKW");
    jweProtHdr.AppendString("enc","A256GCM");

    Thanks!!


    • Marked as answer by Hiline1961 Monday, May 20, 2019 9:27 PM
    • Edited by Hiline1961 Monday, May 20, 2019 9:28 PM
    Monday, May 20, 2019 9:26 PM