android base64 和 aes 加密 解密

package pioneerbarcode.ccw.com.encryptanddecode;

import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.text.TextUtils;import android.util.Base64;import android.view.View;import android.widget.Button;import android.widget.TextView;

import pioneerbarcode.ccw.com.encryptanddecode.utils.AesUtils;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button btnBase64New;    private Button btnBase64Older;    private TextView tvOlder;    private String strOlderData;    private TextView tvJiaMiData;    private TextView tvJieMiData;    private Button btnAesJiaMi;    private Button btnAesjieMi;    private TextView tvAesJiaMiData;    private TextView tvAesJieMiData;
    private static String AESPASSWORD = "hehehe";
    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        setView();        setListener();    }

private void setListener() {        btnBase64New.setOnClickListener(this);        btnBase64Older.setOnClickListener(this);        btnAesJiaMi.setOnClickListener(this);        btnAesjieMi.setOnClickListener(this);    }

private void setView() {        btnBase64New = (Button) findViewById(R.id.btn_base64_jiemi);        btnBase64Older = (Button) findViewById(R.id.btn_base64_jiami);        tvOlder = (TextView) findViewById(R.id.tv_older);        tvJiaMiData = (TextView) findViewById(R.id.tv_jiami_data);        tvJieMiData = (TextView) findViewById(R.id.tv_jiemi_data);

btnAesJiaMi = (Button) findViewById(R.id.btn_Aes_jiami);        btnAesjieMi = (Button) findViewById(R.id.btn_Aes_jiemi);        tvAesJiaMiData = (TextView) findViewById(R.id.tv_Aes_jiami_data);        tvAesJieMiData = (TextView) findViewById(R.id.tv_Aes_jiemi_data);

strOlderData = tvOlder.getText().toString().trim();    }

@Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.btn_base64_jiemi:                //base64 解密                base64Decode();                break;            case R.id.btn_base64_jiami:                //Base64加密                base64Encrypt();                break;            case R.id.btn_Aes_jiami:                //Aes 加密                aesEncrypt();                break;            case R.id.btn_Aes_jiemi:                //Aes 解密                aesDecode();                break;            default:                break;        }    }

/**     * Aes 解密     */    private void aesDecode() {        try {            if (!TextUtils.isEmpty(tvAesJiaMiData.getText().toString().toString().trim())) {                // Aes 解密后的数据                String data = AesUtils.decrypt(AESPASSWORD, tvAesJiaMiData.getText().toString().trim());                tvAesJieMiData.setText(data);            }        } catch (Exception e) {            e.printStackTrace();        }    }

/**     * Aes 加密     */    private void aesEncrypt() {        try {            String data = AesUtils.encrypt(AESPASSWORD, strOlderData);            //加密后的串            tvAesJiaMiData.setText(data);        } catch (Exception e) {            e.printStackTrace();        }    }

/**     * base64解密     */    private void base64Decode() {        if (!TextUtils.isEmpty(tvJiaMiData.getText().toString().trim())) {            String data = new String(Base64.decode(tvJiaMiData.getText().toString().trim().getBytes(), Base64.DEFAULT));            tvJieMiData.setText(data);        }    }

/**     * base64加密     */    private void base64Encrypt() {        //下面是两种方式 加密        //// 在这里使用的是encode方式,返回的是byte类型加密数据,可使用new String转为String类型//        String olderData_base64 = new String(Base64.encode(strOlderData.getBytes(), Base64.DEFAULT));        //// 加密传入的数据是byte类型的,并非使用decode方法将原始数据转二进制,String类型的数据 使用 str.getBytes()即可        String olderData_base64 = Base64.encodeToString(strOlderData.getBytes(), Base64.DEFAULT);        tvJiaMiData.setText(olderData_base64);    }

}
public class AesUtils {    public static String encrypt(String seed, String cleartext) throws Exception {        byte[] rawKey = getRawKey(seed.getBytes());        byte[] result = encrypt(rawKey, cleartext.getBytes());        return toHex(result);    }

public static String decrypt(String seed, String encrypted) throws Exception {        byte[] rawKey = getRawKey(seed.getBytes());        byte[] enc = toByte(encrypted);        byte[] result = decrypt(rawKey, enc);        return new String(result);    }

private static byte[] getRawKey(byte[] seed) throws Exception {        KeyGenerator kgen = KeyGenerator.getInstance("AES");        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");        sr.setSeed(seed);        kgen.init(128, sr); // 192 and 256 bits may not be available        SecretKey skey = kgen.generateKey();        byte[] raw = skey.getEncoded();        return raw;    }

private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");        Cipher cipher = Cipher.getInstance("AES");        cipher.init(Cipher.ENCRYPT_MODE, skeySpec,new IvParameterSpec(new byte[cipher.getBlockSize()]));        byte[] encrypted = cipher.doFinal(clear);        return encrypted;    }

private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");        Cipher cipher = Cipher.getInstance("AES");        cipher.init(Cipher.DECRYPT_MODE, skeySpec,new IvParameterSpec(new byte[cipher.getBlockSize()]));        byte[] decrypted = cipher.doFinal(encrypted);        return decrypted;    }

private static String toHex(String txt) {        return toHex(txt.getBytes());    }    private static String fromHex(String hex) {        return new String(toByte(hex));    }

private static byte[] toByte(String hexString) {        int len = hexString.length()/2;        byte[] result = new byte[len];        for (int i = 0; i < len; i++)            result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();        return result;    }

private static String toHex(byte[] buf) {        if (buf == null)            return "";        StringBuffer result = new StringBuffer(2*buf.length);        for (int i = 0; i < buf.length; i++) {            appendHex(result, buf[i]);        }        return result.toString();    }    private final static String HEX = "0123456789ABCDEF";    private static void appendHex(StringBuffer sb, byte b) {        sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));    }}

经过验证可用
				
时间: 2024-10-25 09:22:31

android base64 和 aes 加密 解密的相关文章

iOS,Android,Jave后台AES加密解密

AES256 在iOS和Android上的相关代码: http://www.tuicool.com/articles/RVFbmmU 里面可以下载相关的代码. 我们遇到的问题是: 把Android的代码移动到Java 后台出现无法加密. 遇到如下的2个问题 1. no cipher getinstance support for AES/CBC/PKCS7Padding 解决方案: http://www.codeweblog.com/java-%E4%BD%BF%E7%94%A8aes-cbc-

java使用AES加密解密 AES-128-ECB加密

http://www.cnblogs.com/chen-lhx/p/5817161.html ************************************************* import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; /** * * @author Administrator * */ pub

移动开发---AES加密解密

aes加密解密 ? import android.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * Date: 2019/4/1 * autor:Wayne */ public class AESUtil { private static String key = "123456789&qu

java进阶12 Base64 UrlBase64 Hex 加密 解密技术

java的加密与解密技术: 现在的加密技术主要有 单向加密算法:以MD5 SHA算法为代表 对称加密算法:以DES 三重DES AES PBE算法为代表 非对称加密算法:以RSA为代表 简要的说下这三种加密算法的区别 先是单向加密算法,顾名思义,它不会有密钥,因为它是单向的,加密之后无法解密,就连程序猿都无法知道加密之后的东西是什么 主要用处是数据完整性的验证. 对称加密算法,其特征是公钥与私钥相同.一般用来数据储存,比如将数据加密之后存入数据库,那么数据库管理员就无法泄密数据库中的类容 有密钥

php与java通用AES加密解密算法

php与java通用AES加密解密算法 AES指高级加密标准(Advanced Encryption Standard),是当前最流行的一种密码算法,在web应用开发,特别是对外提供接口时经常会用到,下面是我整理的一套php与java通用的AES加密解密算法. php版代码如下: <?php class CryptAES { protected $cipher = MCRYPT_RIJNDAEL_128; protected $mode = MCRYPT_MODE_ECB; protected

JAVA中使用AES加密解密

技术交流群: 233513714 /** * AES加密测试 * * @param str 加密参数 */ public void aesTest(String str) { log.info("[rsaTest获取请求:{}]", str); try { String encryptResult = AESUtil.encrypt(str, "123456"); log.info("[AES加密后的参数为:{}]", encryptResult

ruby AES加密解密

最近和京东合作做一个项目,在接口对接传递参数时,参数需要通过AES加密解密. 本来想到用gem 'aescrypt'处理,但是aescrypt的编码方式用的base64,而京东那边用的是16进制.所以就自己写了加密解密方法. AES 加密 def aes_encrypt(key, encrypted_string) aes = OpenSSL::Cipher::Cipher.new("AES-128-ECB") aes.encrypt aes.key = key txt = aes.u

C# 实现 JAVA AES加密解密[原创]

以下是网上普遍能收到的JAVA AES加密解密方法. 因为里面用到了KeyGenerator 和 SecureRandom,但是.NET 里面没有这2个类.无法使用安全随机数生成KEY. 我们在接收JAVA发送的AES加密字符串后,在.NET没有对应的KeyGenerator 和 SecureRandom去生成AES 的 KEY值,导致无法直接解密. 1 import java.security.SecureRandom; 2 import java.util.Base64; 3 4 impor

iOS之AES加密解密

//AES加密解密#import <CommonCrypto/CommonCrypto.h>#import <CommonCrypto/CommonDigest.h> //AES128位加密 base64编码 注:kCCKeySizeAES128点进去可以更换256位加密 -(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key { char keyPtr[kCCKeySizeAES128+1];//