简体   繁体   中英

Convert Encryption Algorithm from VB.NET to Java (Android)

i'm using the following algorithm to encrypt and decrypt a string in VB.NET and wanted to do that same method in Android also. can anyone tell me the similar algorithm for Android (Java)

Encryption:

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

Decryption:

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
  1. For the Cipher, use Cipher.getInstance("DES/ECB/PKCS5Padding")
  2. For getting the bytes to input in the hash function to get the key, use String.getBytes(key, Charset.forName("ASCII")) and new String(keyData, Charset.forName("ASCII")) the other way round
  3. Use the (as yet unspecified) hash function. Make sure you set the key size to 8 bytes afterwards, as DES only needs 8 characters for the key. Something like MessageDigest.getInstance("MD5") or "SHA1" should do the trick.
  4. Create the key by simply performing new SecretKeySpec(<my 8 byte byte array>, "DES")
  5. Base 64 encoding/Decoding is not installed by default, look into commons-codec from Apache to do this.

If you use character encodings at several places, just create a constant:

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

The new and improved way of getting part of a byte array is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM