android - android中的加密

标签 android

如何在 Android 中使用 Triple DES 进行加密?是否有可用的预定义类?

最佳答案

这可能适合您,也可能不适合您。 玩得开心,日航

 public BoolString tryEncrypt(String inString, String key){
        boolean success= true;
        String err="";
        String outString="Encrypted"; // BoolString.value

        try {
            byte[] byteKey= key.getBytes("UTF8");   
            if (byteKey.length != 24) {
                success= false;
                err= "Key is "+byteKey.length+" bytes. Key must be exactly 24 bytes in length.";
                throw new Exception(err); // could also return here
            }
            KeySpec ks= new DESedeKeySpec(byteKey); 
            SecretKeyFactory skf= SecretKeyFactory.getInstance("DESede");
            SecretKey sk= skf.generateSecret(ks);
            Cipher cph=Cipher.getInstance("DESede");
            cph.init(Cipher.ENCRYPT_MODE, sk);
            byte[] byteInString= inString.getBytes("UTF8");
            byte[] byteEncoded= cph.doFinal(byteInString);
            outString= Base64.encodeToString(byteEncoded, Base64.DEFAULT);
        }
        catch (UnsupportedEncodingException e){err="Unable to convert key to byte array."; success= false;}
        catch (InvalidKeyException e){err="Unable to generate KeySpec from key";success= false;} 
        catch (NoSuchAlgorithmException e){err="Unable to find algorithm.";success= false;}
        catch (InvalidKeySpecException e){err="Invalid Key Specification";success= false;}
        catch (NoSuchPaddingException e){err="No such padding";success= false;}
        catch (IllegalArgumentException e){err="Illegal argument";success= false;}   
        catch (Exception e){err=e.getMessage();success= false;}

        return new BoolString(success,err,outString);
    }

// a utility class to signal success or failure, return an error message, and return a useful String value
// see Try Out in C#
public final class BoolString {
    public final boolean success;
    public final String err;
    public final String value;

    public BoolString(boolean success, String err, String value){
        this.success= success;
        this.err= err;
        this.value= value;
    }
}

关于android - android中的加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4907520/

相关文章:

c# - 在添加自己的 LinearLayout 期间无法激活 JNI 句柄 - Xamarin Android

android - 显示进度条直到从服务器下载图像

android - 在android中同时setonclicklistener和setontouchlistener

android - 如何使用数组名的动态键创建一个 pojo 类

Android - GridLayout 单元格大小

android - PendingIntent 上的 "requestCode"用于什么?

android - 创建穿戴应用程序 XML : AAPT: error: attribute android:boxedEdges not found 时面临问题

android - 在 Android 中按像素滚动 ListView

android - 损坏的 AVD 系统路径 - 但 ANDROID_SDK_ROOT 已定义且正确?

java - 如何减少图表引擎中饼图的边距大小?