How to use 3DES algorithm on Android?

后端 未结 2 558
盖世英雄少女心
盖世英雄少女心 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: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;
             }
         }
    

提交回复
热议问题