-1

This is my following function for encryption of simple string in .Net.Now i want the result same as the following function return in java.

public static string EncryptPasswordWithKey(string strToEncrypt, string strKey)
    {
      try
      {
        TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();            
        MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
        byte[] byteHash, byteBuff;
        string strTempKey = strKey;
        byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
        objHashMD5 = null;
        objDESCrypto.Key = byteHash;
        objDESCrypto.Mode = CipherMode.ECB; ////CBC, CFB
        byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
        return Convert.ToBase64String(objDESCrypto.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));            
      }
      catch (Exception ex)
      {
        return "Wrong Input. " + ex.Message;
      }
    }

Output: Admin = "hYqyTjl+nrk="

Can any one having solution on this.

Sachin
  • 47
  • 3
  • 10
  • please do some research before asking question directly. you will surely get the solution on the first page of google itself. – Mehul Joisar Aug 12 '14 at 08:54
  • @MehulJoisar:I cant find an proper way to google it. – Sachin Aug 12 '14 at 08:57
  • possible duplicate of [.NET TripleDESCryptoServiceProvider equivalent in Java](http://stackoverflow.com/questions/1400830/net-tripledescryptoserviceprovider-equivalent-in-java) – Mehul Joisar Aug 12 '14 at 09:12
  • How about replacing the crypto on both sides with something secure (such as AES-GCM with a proper nonce) instead of porting insecure crypto? – CodesInChaos Aug 12 '14 at 10:16

1 Answers1

0

I think this will work:

    private static final String AES = "AES";

    private static String encrypt(final String strKey, final String strToEncrypt) {
        SecretKeySpec secKeySpec = null;
        Cipher cipher = null;
        byte[] encrypted = null;
        try {
            secKeySpec = new SecretKeySpec(strKey.getBytes(), "AES");
            cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.ENCRYPT_MODE, secKeySpec);
            encrypted = cipher.doFinal(strToEncrypt.getBytes());

        } catch (final Exception e) {
            System.out.println(e);
        }
        return Base64.encodeBase64String(encrypted);
    }

Please note that the AES key length should be 16 bytes.

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
Nikola Dimitrovski
  • 720
  • 1
  • 10
  • 23
  • If i try out with less AES key length how can i do this?? – Sachin Aug 12 '14 at 10:06
  • Check this list to see which algorithm to choose: `http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Cipher`. You can use RC2, RC4 because they support variable-key-size from 40 to 1024 bit – Nikola Dimitrovski Aug 12 '14 at 11:25