将加密功能从.net转换为java

时间:2014-08-12 08:49:25

标签: java android .net encryption password-encryption

这是我在 .Net 中对加密的简单字符串的以下功能。现在我希望结果与以下函数一样返回的的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;
      }
    }

输出:管理员=" hYqyTjl + nrk ="

任何人都可以解决此问题。

1 个答案:

答案 0 :(得分:0)

我认为这会奏效:

    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);
    }

请注意,AES密钥长度应为16个字节。