How to use 3DES algorithm on Android?

后端 未结 2 544
盖世英雄少女心
盖世英雄少女心 2020-12-29 16:49

On the server side, the encyption/decryption of the password field is done in C#.

Now, i need to implement same functionality in my android application. So, i follow

相关标签:
2条回答
  • 2020-12-29 17:11

    Triple DES is called "DESede" (DES using single DES Encrypt, Decrypt, Encrypt for encryption) in both Java and Android runtimes. So it is build in functionality which can be access through the Cipher class. It also lists the available algorithms. For triple DES you could use "DESede/CBC/PKCS5Padding"`. Don't forget to supply it a random IV of 8 bytes.

    Triple DES should only be used for backwards compatibility. If you decide to use it at least supply it 24 bytes of key material, otherwise there is a chance that your ciphertext can be cracked. For a more modern approach use AES, preferably in an authenticated mode such as GCM ("AES/GCM/NoPadding"). Note that GCM requires a unique nonce of 12 bytes.

    0 讨论(0)
  • 2020-12-29 17:35

    Use this code to encrypt your string

    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    
    import android.util.Base64;
    //string encryption
    public class EncryptionHelper {
    
    
    
        // Encrypts string and encode in Base64
        public static String encryptText(String plainText) throws Exception {
            // ---- Use specified 3DES key and IV from other source --------------
            byte[] plaintext = plainText.getBytes();//input
            byte[] tdesKeyData = Constants.getKey().getBytes();// your encryption key
    
            byte[] myIV = Constants.getInitializationVector().getBytes();// initialization vector
    
            Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
            IvParameterSpec ivspec = new IvParameterSpec(myIV);
    
            c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
            byte[] cipherText = c3des.doFinal(plaintext);
            String encryptedString = Base64.encodeToString(cipherText,
                    Base64.DEFAULT);
            // return Base64Coder.encodeString(new String(cipherText));
            return encryptedString;
        }
    
    }
    

    This is how you can encrypt the string

    String encryptedPassword = EncryptionHelper.encryptText(edtText.getText().toString());
    

    EDIT Code for Constants.java

         Class Constants {
             private final String initializationVector = "INITALIZATION_VECTOR";
             private final String ecnryptionKey = "ENCRYPTION_KEY";
             public static String getInitializationVector() {
                 return initializationVector;
             }
             public static String getKey() {
                 return ecnryptionKey;
             }
         }
    
    0 讨论(0)
提交回复
热议问题