Могу ли я получить эквивалентный код точки net из кода java - PullRequest
0 голосов
/ 14 июля 2020

У меня есть один код java, который необходимо преобразовать в код c#.

Java Класс использования

 public class EncryptorDecryptorUtil {
     private int keySize;
      private Cipher cipher;
      
      public EncryptorDecryptorUtil(int keySize)
      {
        this.keySize = keySize;
        try
        {
          this.cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        }
        catch (NoSuchAlgorithmException e)
        {
          e.printStackTrace();
        }
        catch (NoSuchPaddingException e)
        {
          e.printStackTrace();
        }
      }
      
      public String decrypt(String salt, String iv, String passphrase, String EncryptedText)
      {
        String decryptedValue = null;
        try
        {
          byte[] saltBytes = hexStringToByteArray(salt);
          SecretKeySpec sKey = (SecretKeySpec)generateKeyFromPassword(
            passphrase, saltBytes);
          byte[] ivBytes = hexStringToByteArray(iv);
          IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
          this.cipher.init(2, sKey, ivParameterSpec);
          byte[] decordedValue = new BASE64Decoder()
            .decodeBuffer(EncryptedText);
          byte[] decValue = this.cipher.doFinal(decordedValue);
          decryptedValue = new String(decValue);
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
        return decryptedValue;
      }
      
      public static SecretKey generateKeyFromPassword(String password, byte[] saltBytes)
        throws GeneralSecurityException
      {
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), saltBytes, 
          100, 128);
        SecretKeyFactory keyFactory = 
          SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        return new SecretKeySpec(secretKey.getEncoded(), "AES");
      }
      
      public static byte[] hexStringToByteArray(String s)
      {
        System.out.println("s:::::::"+s);
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
          data[(i / 2)] = 
            ((byte)((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)));
        }
        return data;
      }
}

Java Основные методы

public class EncryptionDecryption {
    
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.put("applicationNo","PNB00000000000004016");
        json.put("custID","PNB000000004016");
        
        
        String input = json.toJSONString();
        
        String password = "46ea428a97ba4c3094fc66e112d1d678";

        EncryptionDecryption enc = new EncryptionDecryption();

        String encryptMessage= enc.encryptMessage(input, password);

        System.out.println("Encrypted Message :"+encryptMessage);

        String encrypt2Message = "8b7a1e90d701f55c49e22135eed31c94 89f9af1e83e8c83bdf603f5428ba6f14 0R2A2JDkY8tFR1FZojY7Su9CVI9zjw4yjr/lRElwU75MF5e0LxgOb+Y/DOyVFNd89Ra4YADIZdopLZ5a59Z2BgEjMpSn27tqnGfFvWtfm+eh+A/aVcB2YwfD9rdsd67x6xUb8kmfL7qnO/uxaHyQtqlvwpNRBVjyfRlk1wPfaxyOQa0oEiWRmUXYxEoJ651EhYtHeHKmII7qzDgcioIYUlsBgZUjOu0sNEdiwSvvHbw=";
        String decryptMessage = enc.decryptMessage(encrypt2Message, password);
        System.out.println("decryptMessage Message :"+decryptMessage);
    }


     public String encryptMessage(String txtToEncrypt, String passphrase)
      {
         System.out.println("encryptMessage :txtToEncrypt :"+txtToEncrypt);
        String combineData = "";
        try
        {
          Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
          String saltHex = getRandomHexString(32);
          String ivHex = getRandomHexString(32);
          byte[] salt = hexStringToByteArray(saltHex);
          byte[] iv = hexStringToByteArray(ivHex);
          SecretKeySpec sKey = (SecretKeySpec)generateKeyFromPassword(
            passphrase, salt);
          cipher.init(1, sKey, new IvParameterSpec(iv));
          byte[] utf8 = txtToEncrypt.getBytes("UTF-8");
          byte[] enc = cipher.doFinal(utf8);
          combineData = saltHex + " " + ivHex + " " + 
            new BASE64Encoder().encode(enc);
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
        combineData = combineData.replaceAll("\n", "").replaceAll("\t", "").replaceAll("\r", "");
        return combineData;
      }
      


      public String decryptMessage(String str, String myKey)
      {
        String decrypted = null;
        try
        {
          if ((str != null) && (str.contains(" ")))
          {
            String salt = str.split(" ")[0];
            String iv = str.split(" ")[1];
            String encryptedText = str.split(" ")[2];
            
            EncryptorDecryptorUtil dec = new EncryptorDecryptorUtil(128);
            decrypted = dec.decrypt(salt, iv, myKey, encryptedText);
          }
          else
          {
            decrypted = str;
          }
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
        return decrypted;
      }
      
      public static String getRandomHexString(int numchars)
      {
        Random r = new Random();
        StringBuilder sb = new StringBuilder();
        while (sb.length() < numchars) {
          sb.append(Integer.toHexString(r.nextInt()));
        }
        return sb.toString().substring(0, numchars);
      }
      
      public static byte[] hexStringToByteArray(String s)
      {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
          data[(i / 2)] = 
            ((byte)((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)));
        }
        return data;
      }
      


      public static SecretKey generateKeyFromPassword(String password, byte[] saltBytes)
        throws GeneralSecurityException
      {
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), saltBytes, 
          100, 128);
        SecretKeyFactory keyFactory = 
          SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        return new SecretKeySpec(secretKey.getEncoded(), "AES");
      }
}

Я пробовал приведенный ниже код в. net

public static byte[] hexStringToByteArray(string hexString)
        {

           
            byte[] data = new byte[hexString.Length / 2];
            for (int index = 0; index < data.Length; index++)
            {
                string byteValue = hexString.Substring(index * 2, 2);
                data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
            }

            return data;


        }


 public string generateKey(String password, byte[] saltBytes)
        {
           
            int iterations = 100;
            var rfc2898 =
            new System.Security.Cryptography.Rfc2898DeriveBytes(password, saltBytes, iterations);
            byte[] key = rfc2898.GetBytes(16);
            String keyB64 = Convert.ToBase64String(key);
            return keyB64;
        }

Метод дешифрования в c#

public string DecryptAlter(string salt, string iv, string passphrase, string EncryptedText)
    {
    string decryptedValue = null;
    try
    {
        byte[] saltBytes = hexStringToByteArray(salt);

        string sKey = generateKey(passphrase, saltBytes);
        byte[] ivBytes = hexStringToByteArray(iv);


        byte[] keyBytes = System.Convert.FromBase64String(sKey);


        AesManaged aesCipher = new AesManaged();
        aesCipher.IV = ivBytes;
        aesCipher.KeySize = 128;
        aesCipher.BlockSize = 128;
        aesCipher.Mode = CipherMode.ECB;
        aesCipher.Padding = PaddingMode.PKCS7;
        byte[] b = System.Convert.FromBase64String(EncryptedText);
        ICryptoTransform decryptTransform = aesCipher.CreateDecryptor(keyBytes, ivBytes);
        byte[] plainText = decryptTransform.TransformFinalBlock(b, 0, b.Length);

        var res = System.Text.Encoding.UTF8.GetString(plainText);
        return res;
    }
    catch (Exception e)
    {
        var k = e.Message;
    }
    return "";
}

Не работает. Пожалуйста, помогите мне

1026 * Пароль Шифрование «46ea428a97ba4c3094fc66e112d1d678» 1028 * Зашифрованный текст - 4cdf7b17b7db00d7911498dec913d3e4 1e55c4e950b772685ccfdb831c82fede SCQXvM7GeKxP0jLtX5xbuF0WvBC / C81wwxtYNduUe9lVzaYztaJ8ifivjaCBWd7O2zSa + / A + vtFfdSWSnN5 + RcjWka42QQl4f + yZ8C1Y / efIsUlDVXBXmSEjSUp / 4sflXNz7qg62Ka + atpj0aiG6QvU + T5tnafmsDhx / M3zE + Tg =

Теперь нужно его расшифровать.

Ответы [ 2 ]

1 голос
/ 14 июля 2020

Это то, что я получил до сих пор, чтобы направить вас к окончательному решению. Зашифрованное сообщение содержит соль и iv, которые необходимо извлечь и затем использовать для расшифровки сообщения.

using System;
using System.Globalization;
using System.Security.Cryptography;
                    
public class Program
{
    public static void Main()
    {
        string password = "46ea428a97ba4c3094fc66e112d1d678";
        string encrypt2Message = "8b7a1e90d701f55c49e22135eed31c94 89f9af1e83e8c83bdf603f5428ba6f14 0R2A2JDkY8tFR1FZojY7Su9CVI9zjw4yjr/lRElwU75MF5e0LxgOb+Y/DOyVFNd89Ra4YADIZdopLZ5a59Z2BgEjMpSn27tqnGfFvWtfm+eh+A/aVcB2YwfD9rdsd67x6xUb8kmfL7qnO/uxaHyQtqlvwpNRBVjyfRlk1wPfaxyOQa0oEiWRmUXYxEoJ651EhYtHeHKmII7qzDgcioIYUlsBgZUjOu0sNEdiwSvvHbw=";
        string[] pieces = encrypt2Message.Split(' ');
        string salt = pieces[0];
        string iv = pieces[1];
        string encmessage = pieces[2];
        string decryptMessage = DecryptAlter( salt, iv, password, encmessage);
        Console.WriteLine("decryptMessage Message :"+decryptMessage);

        
    }


    public static byte[] hexStringToByteArray(string hexString)
        {

           
            byte[] data = new byte[hexString.Length / 2];
            for (int index = 0; index < data.Length; index++)
            {
                string byteValue = hexString.Substring(index * 2, 2);
                data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
            }

            return data;


        }

    public static string generateKey(String password, byte[] saltBytes)
        {
           
            int iterations = 100;
            var rfc2898 =
            new System.Security.Cryptography.Rfc2898DeriveBytes(password, saltBytes, iterations);
            byte[] key = rfc2898.GetBytes(16);
            String keyB64 = Convert.ToBase64String(key);
            return keyB64;
        }

    public static string DecryptAlter(string salt, string iv, string passphrase, string EncryptedText)
        {
        string decryptedValue = null;
        try
        {
            byte[] saltBytes = hexStringToByteArray(salt);

            string sKey = generateKey(passphrase, saltBytes);
            byte[] ivBytes = hexStringToByteArray(iv);


            byte[] keyBytes = System.Convert.FromBase64String(sKey);


            AesManaged aesCipher = new AesManaged();
            aesCipher.IV = ivBytes;
            aesCipher.KeySize = 128;
            aesCipher.BlockSize = 128;
            aesCipher.Mode = CipherMode.CBC;
            aesCipher.Padding = PaddingMode.PKCS7;
            byte[] b = System.Convert.FromBase64String(EncryptedText);
            ICryptoTransform decryptTransform = aesCipher.CreateDecryptor(keyBytes, ivBytes);
            byte[] plainText = decryptTransform.TransformFinalBlock(b, 0, b.Length);

            var res = System.Text.Encoding.UTF8.GetString(plainText);
            return res;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        }
        return "";
    }   

}
0 голосов
/ 14 июля 2020
 public string decryptMessage()
        {
           string str="some encrypted message";
            string myKey = "46ea428a97ba4c3094fc66e112d1d678";
            string decrypted = null;
            try
            {
                if ((str != null) && (str.Contains(' ')))
                {
                    string salt = str.Split(' ')[0];
                    string iv = str.Split(' ')[1];
                    String encryptedText = str.Split(' ')[2];
                 
                    decrypted = DecryptAlter(salt, iv, myKey, encryptedText);
                    return decrypted;
                }
                else
                {
                    decrypted = str;
                    return decrypted;
                }
            }
            catch (Exception e)
            {

            }

            return decrypted;

        }



    public string DecryptAlter(string salt, string iv, string passphrase, string EncryptedText)
        {
            string decryptedValue = null;
            try
            {
                byte[] saltBytes = hexStringToByteArray(salt);

                string sKey = generateKey(passphrase, saltBytes);
                byte[] ivBytes = hexStringToByteArray(iv);


                byte[] keyBytes = System.Convert.FromBase64String(sKey);


                AesManaged aesCipher = new AesManaged();
                aesCipher.IV = ivBytes;
                aesCipher.KeySize = 128;
                aesCipher.BlockSize = 128;
                aesCipher.Mode = CipherMode.CBC;
                aesCipher.Padding = PaddingMode.PKCS7;
                byte[] b = System.Convert.FromBase64String(EncryptedText);
                ICryptoTransform decryptTransform = aesCipher.CreateDecryptor(keyBytes, ivBytes);
                byte[] plainText = decryptTransform.TransformFinalBlock(b, 0, b.Length);

                var res = System.Text.Encoding.UTF8.GetString(plainText);
                return res;
            }
            catch (Exception e)
            {
                var k = e.Message;
            }
            return "";
        }

        
...