0

I am trying to reproduce the following encryption/decryption algorithm in Java, but I can't find the alternatives for multiple methods such as Rfc2898DeriveBytes().
How do I do this?
Code in c#:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace myCompany.Entities.Configuration
{
    public static class VideoSourceCryptoHelper
    {
        private const string EncryptionKey = "MyWord";
        private static readonly byte[] Salt = {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
        private const string ErrorText = "***ERROR***";

        **public static string Encrypt(string encryptString, bool suppressException = false)**
        {
            if (string.IsNullOrEmpty(encryptString))
            {
                return string.Empty;
            }
            try
            {
                var clearBytes = Encoding.Unicode.GetBytes(encryptString);
                using (var encryption = Aes.Create())
                {
                    var pdb = new Rfc2898DeriveBytes(EncryptionKey, Salt);
                    encryption.Key = pdb.GetBytes(32);
                    encryption.IV = pdb.GetBytes(16);
                    using (var ms = new MemoryStream())
                    {
                        using (var cs = new CryptoStream(ms, encryption.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(clearBytes, 0, clearBytes.Length);
                        }

                        encryptString = Convert.ToBase64String(ms.ToArray());
                    }
                }
            }
            catch(Exception)
            {
                if (suppressException)
                    return ErrorText;
                else
                    throw;
            }
            return encryptString;
        }

Can anyone give similar code in java that will do what C# does?

The "duplicate" answer shows how to write the decrypt method, but I need the encrypt method, as I wrote above.

Abra
  • 19,142
  • 7
  • 29
  • 41
  • Duplicate of a couple of other SO posts, e.g. [Rfc2898DeriveBytes in java](https://stackoverflow.com/q/24405731), [Converting .Net decryption to Java](https://stackoverflow.com/questions/60387628/converting-net-decryption-to-java). *...The "duplicate" answer shows how to write the decrypt method, but I need the encrypt method, as I wrote above....*: Note that key derivation via `Rfc2898DeriveBytes` is the same for encryption and decryption. – Topaco Feb 01 '23 at 13:45

0 Answers0