NoSuchProviderException when encrypting string with 3DES

让人想犯罪 __ 提交于 2019-12-04 21:07:13

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

    private class Constants 
{
private static final String KEY="QsdPasd45FaSdnLjf";
    private static final String INITIALIZATION_VECTOR="l9yhTaWY";
public static String getKey() 
    {
        return KEY;
    }


    public static String getInitializationVector() 
    {
        return INITIALIZATION_VECTOR;
    }
 }   
    }

This is how you can encrypt the string

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

Sorry, I was being lazy. The line

Cipher ecipher = Cipher.getInstance("DESede/CBC/PKCS5Padding","SunJCE");

shows that you are specifying a particular provider. Normally you would want a very good reason for doing this, for example you might be required to use a FIPS-compliant provider. The SunJCE provider does not exist on Android. Just use the default provider, which you get simply by leaving out that argument. So try:

Cipher ecipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");

Similarly, change

Cipher dcipher = Cipher.getInstance("DESede/CBC/PKCS5Padding","SunJCE");

to

Cipher dcipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!