簡體   English   中英

使用C#CryptoStream的Java等式對字符串進行加密和解密

[英]Encrypting and Decrypting String using a Java equilavent of the C# CryptoStream

我正在尋找用Java開發用於移動平台操作系統的應用程序。

我已經在Windows環境的C#WPF中開發了一個應用程序。 我正在使用cryptostream以便使用以下代碼對字符串進行加密和解密。 下面顯示的代碼僅是加密

public string encrypt(string encryptionString)
    {
        byte[] clearTextBytes = Encoding.UTF8.GetBytes(encryptionString);

        SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

        MemoryStream ms = new MemoryStream();
        byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj");
        byte[] key = Encoding.ASCII.GetBytes("hcxilkqbbhczfeultgbskdmaunivmfuo");
        CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);

        cs.Write(clearTextBytes, 0, clearTextBytes.Length);

        cs.Close();

        return Convert.ToBase64String(ms.ToArray());
    }

加密的字符串存儲在在線數據庫中。 我需要做的是讓Java應用程序能夠從數據庫中讀取字符串,並使用來自C#應用程序的相同加密密鑰對字符串進行解密。

謝謝你的幫助。

就個人而言,我喜歡Java加密的BouncyCastle 這段代碼(使用BouncyCastle輕量級API)應該可以解決問題:

String decrypt(byte[] cryptoBytes, byte[] key, byte[] iv) {
    BlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
    cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
    byte[] out = new byte[cipher.getOutputSize(cryptoBytes.length)];
    int offset = cipher.processBytes(cryptoBytes, 0, cryptoBytes.length, out, 0);
    cipher.doFinal(out, offset);
    return new String(out);
}

我發現BouncyCastle的輕量級API比JCE提供程序要痛苦的多,但是您可以根據需要將其用作提供程序。

看起來.net SymmetricAlgorithm和BC的PaddedBufferedBlockCipher默認為PKCS7填充,因此您可以使用默認值。

您可能需要檢出javax.crypto.CipherInputStream和javax.crypto.CipherOutputStream。

http://download.oracle.com/javase/1.5.0/docs/api/javax/crypto/CipherInputStream.html http://download.oracle.com/javase/1.5.0/docs/api/javax/crypto /CipherOutputStream.html

盡管Cipher對象的初始化可能略有不同,但它們的使用方式幾乎與上述示例完全相同。

我使用以下內容在.net和Java之間進行加密

在.net中,我使用:

    /// <summary>
    /// DES Encryption method - used to encryp password for the java.
    /// </summary>
    /// <param name="plainText"></param>
    /// <returns></returns>
    public string EncryptData(string plainText)
    {
        DES des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
        des.Padding = PaddingMode.PKCS7;

        des.Key = Encoding.UTF8.GetBytes(_secretPhrase.Substring(0, 8));
        des.IV = Encoding.UTF8.GetBytes(_secretPhrase.Substring(0, 8));

        byte[] bytes = Encoding.UTF8.GetBytes(plainText);
        byte[] resultBytes = des.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length);

        return Convert.ToBase64String(resultBytes);
    }

    /// <summary>
    /// DES Decryption method - used the decrypt password encrypted in java
    /// </summary>
    /// <param name="encryptedText"></param>
    /// <returns></returns>
    public string DecryptData(string encryptedText)
    {
        DES des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
        des.Padding = PaddingMode.PKCS7;
        des.Key = Encoding.UTF8.GetBytes(_secretPhrase.Substring(0, 8));
        des.IV = System.Text.Encoding.UTF8.GetBytes(_secretPhrase.Substring(0, 8));

        byte[] bytes = Convert.FromBase64String(encryptedText);
        byte[] resultBytes = des.CreateDecryptor().TransformFinalBlock(bytes, 0, bytes.Length);

        return Encoding.UTF8.GetString(resultBytes);
    }

在Java中,我使用:

公共類CryptoUtil {

public static final Logger LOG = Logger.getLogger(CryptoUtil.class);

private Cipher cipher = null;

private SecretKey key = null;

// This variable holds a string based on which a unique key will be generated
private static final String SECRET_PHRASE = "SECRET PHRASE GOES HERE";

// Charset will be used to convert between String and ByteArray
private static final String CHARSET = "UTF8";

 // The algorithm to be used for encryption/decryption DES(Data Encryption Standard)
private static final String ALGORITHM = "DES";

public CryptoUtil() throws DDICryptoException {
    try {
        // generate a key from SecretKeyFactory
        DESKeySpec keySpec = new DESKeySpec(SECRET_PHRASE.getBytes(CHARSET));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        key = keyFactory.generateSecret(keySpec);
        cipher = Cipher.getInstance(ALGORITHM);
    } catch (Exception e) {
        LOG.error(e);
        throw new DDICryptoException(e);
    }
}


/**
 * This method takes a plain text string and returns encrypted string using DES algorithm
 * @param plainText
 * @return String
 * @throws DDICryptoException
 */
public String encrypt(String plainText) throws DDICryptoException {
    String encryptedString = null;
    try {
        // initializes the cipher with a key.
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] plainTextAsUTF8 = plainText.getBytes(CHARSET);

        // decrypts data in a single-part or multi-part operation
        byte[] encryptedBytes = cipher.doFinal(plainTextAsUTF8);

        encryptedString = new sun.misc.BASE64Encoder().encode(encryptedBytes);
    } catch (Exception e) {
        LOG.error(e);
        throw new DDICryptoException(e);

    }
    return encryptedString;

}

/**
 * This method takes a plain text string and returns encrypted string using DES algorithm
 * @param encryptedString
 * @return
 * @throws DDICryptoException
 */
public String decrypt(String encryptedString) throws DDICryptoException {    
    String decryptedString = null;
    try {
        byte[] decodedString = new sun.misc.BASE64Decoder().decodeBuffer(encryptedString);

        // initializes the cipher with a key.
        cipher.init(Cipher.DECRYPT_MODE, key);

        // decrypts data in a single-part or multi-part operation
        byte[] decryptedBytes = cipher.doFinal(decodedString);
        decryptedString = new String(decryptedBytes, CHARSET);
    } catch (Exception e) {
        LOG.error(e);
        throw new DDICryptoException(e);
    }
    return decryptedString;
}

}

我已經設法解決了這個問題。 現在解密工作正常。 使用以下代碼

    String plainPassword = "";
            try
            {
                SecretKeySpec key = new SecretKeySpec("hcxilkqbbhczfeultgbskdmaunivmfuo".getBytes("US-ASCII"), "AES");

                IvParameterSpec iv = new IvParameterSpec("ryojvlzmdalyglrj".getBytes("US_ASCII"));

                Cipher cipher = Cipher.getInsta

nce("AES/CBC/PKCS7Padding");

            cipher.init(Cipher.DECRYPT_MODE, key, iv);

            byte[] encoded = cipher.doFinal(Base64.decodeBase64(encryptedPassword.getBytes()));
            plainPassword = new String(encoded);
        }
        catch (Exception ex)
        {
            Log.d("Decryption Error", ex.toString());
        }

        return plainPassword;

現在問題出在加密上。 我使用了相同的代碼,只是將密碼從解密模式更改為加密模式,但是由於某些原因,當我打印出加密的字符串時,它只會打印出一些垃圾,與C#創建的字符串完全不同。 以下是用於加密的代碼

public String encrypt(String plainPasword)
    {
        String password = "";
        try
        {
            SecretKeySpec key = new SecretKeySpec("hcxilkqbbhczfeultgbskdmaunivmfuo".getBytes("US-ASCII"), "AES");

            IvParameterSpec iv = new IvParameterSpec("ryojvlzmdalyglrj".getBytes("US_ASCII"));

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

            cipher.init(Cipher.ENCRYPT_MODE, key, iv);

            byte[] encoded = cipher.doFinal(plainPasword.getBytes());
            password = new String(encoded);


        }
        catch (Exception ex)
        {
            Log.d("Encryption Error", ex.toString());
        }
        return password;
    }

這似乎有什么問題,我無法解決。 謝謝

        StringBuffer strbuf = new StringBuffer(buf.length * 2);
        int i;

        for (i = 0; i < buf.length; i++) {
            if (((int) buf[i] & 0xff) < 0x10) {
                strbuf.append("0");
            }

            strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
        }

您必須對結果字節數組進行編碼,然后才能將其轉換為字符串。 上面的代碼對我有用,而下面的是我的實際加密功能。

public String encrypt(String data) throws Exception{
    try {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        Key k = new SecretKeySpec(key.getBytes(), 0, key.length(), "AES");

        // Calculate ciphertext size.
        int blocksize = 16;
        int ciphertextLength = 0;
        int remainder = data.getBytes().length % blocksize;
        if (remainder == 0) {
            ciphertextLength = data.getBytes().length + blocksize;
        } else {
            ciphertextLength = data.getBytes().length - remainder + blocksize;
        }


        cipher.init(Cipher.ENCRYPT_MODE, k);
        byte[] buf = new byte[ciphertextLength];
        cipher.doFinal(data.getBytes(), 0, data.length(), buf, 0);

        StringBuffer strbuf = new StringBuffer(buf.length * 2);
        int i;

        for (i = 0; i < buf.length; i++) {
            if (((int) buf[i] & 0xff) < 0x10) {
                strbuf.append("0");
            }

            strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
        }
        return strbuf.toString();
    } catch (Exception e) {
        Logger.logException(e);
    }
    return null;
}

請參閱關於Java中的CryptoStream .NET的答案#5

請務必閱讀底部的評論...

KeySpec ks = new DESKeySpec("key12345".getBytes("UTF-8")); SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(ks);
IvParameterSpec iv = new IvParameterSpec( Hex.decodeHex("1234567890ABCDEF".toCharArray()));
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] decoded = cipher.doFinal(Base64.decodeBase64("B3xogi/Qfsc="));
System.out.println("Decoded: " + new String(decoded, "UTF-8"));

希望這可以幫助...
JK

Cemeron,整潔的代碼!

我遇到了一個有趣的情況,我們的客戶給IV密碼密鑰相同。

在嘗試了遇到糟糕的填充異常的各種組合之后,有效的解決方案是

byte[] iv=new byte[8]; // assuming RC2
System.arraycopy(key.getBytes(), 0, iv, 0, key.getBytes().length > iv.length ? key.getBytes().length);

// Now decrypt and hopefully this should work

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM