【问题标题】:Convert Encryption Algorithm from VB.NET to Java (Android)将加密算法从 VB.NET 转换为 Java (Android)
【发布时间】:2011-12-21 06:38:02
【问题描述】:

我正在使用以下算法在 VB.NET 中加密和解密字符串,并希望在 Android 中也使用相同的方法。谁能告诉我Android(Java)的类似算法

加密:

Private Function decryptStr(ByVal key As String, ByVal enc As String) As String
    Try
        DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))
        DES.Mode = System.Security.Cryptography.CipherMode.ECB
        Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateDecryptor
        Dim Buffer As Byte() = Convert.FromBase64String(enc)
        respass = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
        Return respass
    Catch ex As Exception
        Return enc
    End Try
End Function

解密:

Public Function decryptStr(ByVal encrypted As String, ByVal key As String) As String
    Try
        DES.Key = Hash.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))
        DES.Mode = System.Security.Cryptography.CipherMode.ECB
        Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = DES.CreateEncryptor
        Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(encrypted)
        respass = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
        Return respass
    Catch ex As Exception
        Return encrypted
    End Try
End Function

【问题讨论】:

  • 看看this
  • 使用哪种散列算法(参见“散列”变量的初始化)?

标签: java android vb.net encryption


【解决方案1】:
  1. 对于密码,使用Cipher.getInstance("DES/ECB/PKCS5Padding")
  2. 要获取要在哈希函数中输入的字节以获取密钥,请反过来使用 String.getBytes(key, Charset.forName("ASCII"))new String(keyData, Charset.forName("ASCII"))
  3. 使用(尚未指定的)散列函数。确保之后将密钥大小设置为 8 个字节,因为 DES 只需要 8 个字符作为密钥。 MessageDigest.getInstance("MD5")"SHA1" 之类的东西应该可以解决问题。
  4. 只需执行new SecretKeySpec(<my 8 byte byte array>, "DES")即可创建密钥
  5. 默认未安装 Base 64 编码/解码,请查看 Apache 的 commons-codec 来执行此操作。

如果您在多个地方使用字符编码,只需创建一个常量:

private static final Charset ASCII = Charset.forName("ASCII");

获取字节数组的一部分的新的和改进的方法是:

Arrays.copyOfRange(byte[] original, int from, int to): byte[]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2011-02-26
    • 2013-07-05
    • 2018-11-10
    • 2017-09-19
    相关资源
    最近更新 更多