AES加密解密(CBC模式),androidapp开发工具

这篇博客详细介绍了在Android应用中使用AES加密解密的过程,包括CBC模式的实现。示例代码展示了如何在按钮点击事件中进行加密和解密操作,并提供了AES加密类的完整实现。
摘要由CSDN通过智能技术生成

switch (view.getId()) {

case R.id.btn_encryption://加密

String encryptionString = encryptionContext.getText().toString().trim();

if (TextUtils.isEmpty(encryptionString)) {

Toast.makeText(mContext, “请输入加密内容”, Toast.LENGTH_SHORT).show();

return;

}

try {

String encrypt = AES.getInstance().encrypt(encryptionString.getBytes(“UTF8”));

tvEncryption.setText(encrypt);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

break;

case R.id.btn_decode://解密

String decodeString = tvEncryption.getText().toString().trim();

if (TextUtils.isEmpty(decodeString)) {

Toast.makeText(mContext, “请先加密”, Toast.LENGTH_SHORT).show();

return;

}

String decrypt = AES.getInstance().decrypt(decodeString);

tvDecode.setText(decrypt);

break;

}

}

}

AES

package tsou.com.encryption.aescbc;

import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

/**

  • http://blog.csdn.net/qq_33237207/article/details/53114122

*/

public class AES {

private final String CIPHERMODEPADDING = “AES/CBC/PKCS5Padding”;// AES/CBC/PKCS7Padding

private SecretKeySpec skforAES = null;

private static String ivParameter = “1234huangxiaoguo”;// 密钥默认偏移,可更改

private byte[] iv = ivParameter.getBytes();

private IvParameterSpec IV;

String sKey = “huangxiaoguo1234”;// key必须为16位,可更改为自己的key

private static AES instance = null;

public static AES getInstance() {

if (instance == null) {

synchronized (AES.class) {

if (instance == null) {

instance = new AES();

}

}

}

return instance;

}

public AES() {

byte[] skAsByteArray;

try {

skAsByteArray = sKey.getBytes(“ASCII”);

skforAES = new SecretKeySpec(skAsByteArray, “AES”);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

IV = new IvParameterSpec(iv);

}

public String encrypt(byte[] plaintext) {

byte[] ciphertext = encrypt(CIPHERMODEPADDING, skforAES, IV, plaintext);

String base64_ciphertext = Base64Encoder.encode(ciphertext);

return base64_ciphertext;

}

public String decrypt(String ciphertext_base64) {

byte[] s = Base64Decoder.decodeToBytes(ciphertext_base64);

String decrypted = new String(decrypt(CIPHERMODEPADDING, skforAES, IV,

s));

return decrypted;

}

private byte[] encrypt(String cmp, SecretKey sk, IvParameterSpec IV,

byte[] msg) {

try {

Cipher c = Cipher.getInstance(cmp);

c.init(Ci

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值