前言:
对于3DES加密,在博文 3DES 加密 已经有了详细说明,这边博文将其用Android 实现。
更多的加密可以看:
实例:
实现的详细代码同 AES 加密的实例,针对3DES 算法,抽象函数实现的定义在DESedeEncryption 类中:
public class DESedeEncryption extends BlockEncryption {
// length of key must be 16 bytes or 24(3 * 8) bytes.
private static final String DEFAULT_KEY = "shiftencrypt0926";
public static final String ALGORITHM = "DESede";
private static final int DES_BLOCK_SIZE = 8;
public DESedeEncryption() {
}
public DESedeEncryption(Context context, boolean deleteSrcFile, EncryptionCallback callback) {
super(context, deleteSrcFile, callback);
}
@Override
public Cipher getCipher(int mode) {
return BlockEncryptionHelper.getCipher(mode, ALGORITHM, DEFAULT_KEY);
}
@Override
public String getAlgorithm() {
return ALGORITHM;
}
@Override
protected int getBlockSize() {
return DES_BLOCK_SIZE;
}
}
Activity 的button 部分如下:
private void testEncryption3DES() {
Button edesede = (Button) findViewById(R.id.encrypt_desede);
edesede.setOnClickListener(this);
Button ddesede = (Button) findViewById(R.id.decrypt_desede);
ddesede.setOnClickListener(this);
}
private void desedeEncryption() {
{
mOperationTitle.setText(getString(R.string.encrypt_desede));
String strSource = "hliuhiufhliuhsd;jfijso;goshgosjogijsgo;j";
mBeforeOperation.setText(getString(R.string.before_operation, strSource));
DESedeEncryption encryption = new DESedeEncryption();
mStrEncrypted = encryption.strEncryption(strSource);
mAfterOperation.setText(getString(R.string.after_operation, mStrEncrypted));
}
// if (mFileEncryption != null) {
// Log.d(TAG, "==== test file, encryption with 3des ...");
// String filePath = "/storage/emulated/0/hehe.png";
// String destPath = "/storage/emulated/0/2.png";
// mFileEncryption.setAlgorithm(FileEncryption.ALG_MODE_3DES);
// mFileEncryption.start(FileEncryption.MODE_ENCRYPT, filePath, destPath);
// Log.d(TAG, "==== test file, encryption end");
// }
}
private void desedeDecryption() {
{
mOperationTitle.setText(getString(R.string.decrypt_des));
mBeforeOperation.setText(getString(R.string.before_operation, mStrEncrypted));
DESedeEncryption encryption = new DESedeEncryption();
String strDecrypted = encryption.strDecryption(mStrEncrypted);
mAfterOperation.setText(getString(R.string.after_operation, strDecrypted));
}
// if (mFileEncryption != null) {
// Log.d(TAG, "==== test file, decryption with 3des ...");
// String filePath = "/storage/emulated/0/hehe.png";
// String destPath = "/storage/emulated/0/2.png";
// mFileEncryption.setAlgorithm(FileEncryption.ALG_MODE_3DES);
// mFileEncryption.start(FileEncryption.MODE_DECRYPT, destPath, filePath);
// Log.d(TAG, "==== test file, decryption end");
// }
}
注释的部分为文件加密、解密,同样是实用的。
结果: