0

We have the application done C# and passing parameter to Java application. To make it secure we Java application developer come up with AES encryption. The developer gave sample code in Java. Kindly somebody helps me. How can I encrypt same way in C#

//    Cryptix imports
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import cryptix.provider.key.RawSecretKey;
import cryptix.util.core.Hex;

import xjava.security.Cipher;

public class AESEncryption {

    private Cipher m_alg;
    private RawSecretKey m_key;

    private static final String RIJNDAEL = "Rijndael"; //mode of encryption
    private static final String PROVIDER_CRYPTIX = "Cryptix"; // Cryptography algorithm providers

    /**
     * Must (once) be dynamically installed. - could alternatively be set
     * statically in $JAVAHOME/lib/security by changing security provider.
     *
     */
    static {
        java.security.Security.addProvider(new cryptix.provider.Cryptix());
        System.out.println(" Java Security - Add security provider - Cryptix provider added");
    }

    public AESEncryption(String secretKey)
        throws java.security.NoSuchProviderException, java.security.NoSuchAlgorithmException {

        //System.out.println("Key used for encryption/decryption :- " + secretKey);

        m_alg = Cipher.getInstance(RIJNDAEL, PROVIDER_CRYPTIX);
        m_key = new RawSecretKey(RIJNDAEL, Hex.fromString(secretKey));

    }

    /**
     * encrypt supplied string.
     *
     * @param str to encrypted
     * @return encrypted String
     */
    public String encrypt(String str) throws java.security.KeyException {
        byte[] ect = null;
        str = convert(str); // pad if necessary
        //System.out.println("String to encrypt [ " + str + " ]");

        m_alg.initEncrypt(m_key);
        ect = m_alg.crypt(str.getBytes());

        //System.out.println("Encrypted String [ " + Hex.toString(ect) + " ]");
        return Hex.toString(ect);
    }

    public String decrypt(String str) throws java.security.KeyException {
        byte[] dct = null;
        String decryptedString;

        //System.out.println("String to decrypt [ " + str + " ]");
        m_alg.initDecrypt(m_key);
        dct = m_alg.crypt(Hex.fromString(str));

        decryptedString = new String(dct);
        //System.out.println("Decrypted String [ " + decryptedString + " ]");

        return decryptedString.trim();
    }

    /**
     * Internal routine to convert a string to a byte array and to
     * pad the byte array (with 0) in order ot fill out the final block.
     *
     * padding value based on Cipher's defined block size.
     *
     * @param str
     * @return
     */
    private String convert(String str) {
        int padding = 0, sourceLength = 0, i, blockSize;

        sourceLength = str.length();
        blockSize = m_alg.blockSize();

        padding = blockSize - (sourceLength % blockSize);

        if (padding != blockSize) {

            for (i = 0; i < padding; i++) {
                str = str + " ";
            }
        }
        return str;
    }

    public static void main(String[] args) {

        try {
            AESEncryption tcase = new AESEncryption("27323A0825226DDD316881852610DACB81210355C3117DAD83EF5EE9E8602915");
            String params ="accentué";

            System.out.println("Params Before:" + params);
            String encrypted = tcase.encrypt(params);
            System.out.println("Params Encrypted:" + encrypted);

            String enc = "E669500CF68CCD88CBA54EDAA07E30A57E8C8518101D0D7C36323194222D6B4393AC2B22A914E902F47C89BC0CE1BCE67A14066219C3480875E1D75536AE0009899C23E644F0C701AE6EBB4DB0C1EDCF9A3A7FFA9BE117237083B5EC4B4EE7FBEBB94D7526C4C9E23EA38E2B2B526E8005265817FC505974DACAA55D3AA50FCE3440BFE79447135D071443DAE4013F2C32CDA00F4AFC2194B616FA50A1BF688F53336194B156E709818DD323F574CDA83A0716F7C22572278D9C162DC8DBC000AEF4C972E6FD203706CFFBE6143130CEB78D4F1CD77B64352766A9C2885AF66B1F81C11A4C71B2B1BF662AD854D429A8356B8FD91B1083ACDAD1DDE3BFF1353D108E2E133558324E63EE9DC13CB4B34BEE494C674BC7BB8C7E77B936AB16BC320E303A34B7510A438C9A9D7E212C3CA3F6771A7DD0CC1AB8A9D1B89FD850B343C7E8828A0155C1A30FA78B250EB073000C9D4F39EA8BF6AE8C19A0BA32EC222DF4BC59396F2396E4FBAB4599EE28E63F068E33614CF84D98D1FEF504E5DCC5940CF17294B6910845A9DDD8805833E1DB1C3CBF0658D1388A65546D58CE465E0E4FA941B6635E1A7042048C1B64456C3EAF9D331E3889E55E37CE71201C7B34526FF2C9297E52F7CBCC7603809566AE4AE3AE644BA826A130DA71DD201532C564F0B11E17306DF061DCF74AD6062931AD09D75345B11933D293945557755788E5C39D1485E87B8C20ED983EA977B9D9CDD7D8E3112D858061A6C376FB37A4E6292B0E4640A05A850175382E385F7F095CAFED9DFCBBEA6C10AA571EE8D01D6022CC240CCDD22EA374D619B4191F619DFB574EBFA80BAEC393F7FCD111789C96AA3DFA1E58E60EEB712F4C4A41506E38A7BF9CF24BFDEF2B7FE6E25C1D9ADAC11EA3CCF6F187A7446A9933D4C4BB25DE8467592D2457F7674E13D087B47221C0EBB8716F312FF52E46EA77566364346D2D899228F0C99737C4AD2A95C9CF892F89430CA1EEEFA68CE85321E5A4A44E71B6C4C62C8D3623E6103D9638A7DC0E66A249F130365773A3530F8F8F1FC4C57B4BEC296C1A0DD190646F2F3A427DE54155E6772FADF7A09488F45AE7CBA9C2F90BD3205D97E00C8CF62AB5FBEC774CA457A38E351FF110B8AA799918AE93E864862EE2F3B5D997D6C249613283337D83A60BDF3490BB73EB2A948A71D61E433F58A537693364D131DD7787D4D4A9C6EE891AB5B783A4F7B6009127D72A1F184ADA2BE20647EB6FE15FACDDF43A03BA9FE120E552A2BA14F568D65187C1F2E6108699C405018A3447A149C0A5196504201677E37CE789246D48A5270B59597D9F77F75E7CF23B18B51D5F25E37258BB231CE0E9FD3E5B21D14F1541A76F4875F231038751A36A79C84C4EBF9F2146506EC8DF6EBDD0CFECCBF388D9020CC5656322BF695D3ED716FAF0545040830815B550075F5D2301C6469F5DD99E5FD0093C4A";
            //String decrypted = tcase.decrypt(encrypted);
            String decrypted = tcase.decrypt(enc);
            System.out.println("Params Decrypted:" + decrypted);

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (java.security.KeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }

}
gorkem
  • 731
  • 1
  • 10
  • 17
Milind
  • 1,855
  • 5
  • 30
  • 71
  • To get answered - what EXACTLY are you struggling with? (using system.security.cryptography ?) – gusto2 May 24 '17 at 08:07
  • I tried that but secrete key is 64 Character, which it tells invalid – Milind May 24 '17 at 08:11
  • AFAIK C# & Java have different default cipher mode mechanism - C# uses CBC while Java utilize ECB when defining keys (and ECB knowingly insecure: https://stackoverflow.com/a/6671819/900284). You need to specify which cipher method you want to convert into & where the code stopped working. – Tetsuya Yamamoto May 24 '17 at 08:15
  • @Milind From the code I assume the secret is a string in hexadecimal format. You have to convert it to array of bytes ( 64 hexadecimal chars = 32 bytes = 256 bit) – gusto2 May 24 '17 at 08:16
  • @Milind plus I see the security is very basic (no nonce, no authenticated encryption, manual padding, I don't see mode defined (I am not sure what the default is for Cryptix library)) – gusto2 May 24 '17 at 08:21
  • @gusto2 Kindly can you help me how we can do that – Milind May 24 '17 at 08:21
  • And what EXACTLY are you struggling with? decryption: http://www.obviex.com/samples/Encryption.aspx , for the key - convert the hex string to byte array. With the developer you have to agree on the common parameters (AES-128 or 256? Mode ECB (unsafe), CTR, CBC? for longer data than a single block) nobody won't do the code for you here. Still keep in mind doing encryption properly takes more than just encrypt a block of data, so maybe it would be good enough for you now, but still until you both know what are you doing, assume it won't be perfect – gusto2 May 24 '17 at 08:29

1 Answers1

0

İf you used IV vector in c# while encrypted data with AES . You should use IV vector in Java

c#

 using (var random = new System.Security.Cryptography.RNGCryptoServiceProvider())
        {
            var key = new byte[16];
            random.GetBytes(key);

            using (System.Security.Cryptography.AesCryptoServiceProvider aesAlg = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                aesAlg.BlockSize = 128;
                aesAlg.KeySize = 128;
                aesAlg.Key = key;
                aesAlg.IV = key;
                aesAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
                aesAlg.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                using (ICryptoTransform iCryptoper = aesAlg.CreateEncryptor())
                {
                    byte[] encryptedData = iCryptoper.TransformFinalBlock(x509CertData, 0, x509CertData.Length);
                    string encodedCert = Convert.ToBase64String(encryptedData);

                    System.Security.Cryptography.X509Certificates.X509Certificate2 x509Cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(x509CertData);
                    System.Security.Cryptography.RSACryptoServiceProvider provider = (System.Security.Cryptography.RSACryptoServiceProvider)x509Cert.PublicKey.Key;
                    byte[] encrypted = provider.Encrypt(aesAlg.Key, false);
                    string test = Convert.ToBase64String(encrypted);


                }

            }
        }

java

javax.crypto.SecretKey sc = new javax.crypto.spec.SecretKeySpec(secretKey, "AES");
Cipher dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
dcipher.init(Cipher.DECRYPT_MODE, sc, ivParameterSpec);
byte[] decyrptedCert = dcipher.doFinal(java.util.Base64.getDecoder().decode(stringToDecrypt));
alex.pulver
  • 2,107
  • 2
  • 31
  • 31