Android代码中加解密方式

加解密方式有很多种;大体可分成,Base64加密、单向加密(MD5、SHA)、对称加密(DES,AES)、非对称加密(RSA)、非数字签名等等,对于每种方式不多说了,直接看代码吧~~~

Base64算法 
Base64是一种基于64个基本字符,加密后的内容只包含这64个字符;它是一种最简单的算法,只是我们肉眼看不出来罢了,一般用于加密ulr.

package com.app.sercet;
import java.util.Base64;

public class Base64Demo {

    /**
     * Base64加密
     * @param str
     * @return
     */
    private static String encode(String str) {
        byte[] encodeBytes = Base64.getEncoder().encode(str.getBytes());
        return new String(encodeBytes);
    }

    /**
     * Base64解密
     * @param str
     * @return
     */

    private static String decode(String str) {
        byte[] decodeBytes = Base64.getDecoder().decode(str.getBytes());
        return new String(decodeBytes);
    }
    }

单向加密算法 
包含MD5和SHA,就是只能加密不能解密;下面上代码

MD5(消息摘要算法)

package com.app.sercet;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Demo {

    // MD5加密
    private static String toMd5(String str) {

        // 实例化一个指定摘要算法为MD5的MessageDigest对象
        MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance("MD5");
            // 重置摘要以供再次使用
            algorithm.reset();
            // 使用bytes更新摘要
            algorithm.update(str.getBytes());
            // 使用指定的byte数组对摘要进行最后更新,然后完成摘要计算
            return toHexString(algorithm.digest(), "");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    // 将字符串中的每个字符转换为十六进制
    private static String toHexString(byte[] bytes, String separtor) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append("0");
            }
            hexString.append(hex).append(separtor);
        }
        return hexString.toString();
    }
}

SHA(安全散列算法)

package com.app.sercet;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHADemo {

    // MD5加密
    private static String toSHA(String str) {

        // 实例化一个指定摘要算法为MD5的MessageDigest对象
        MessageDigest algorithm;
        try {//e84e30b9390cdb64db6db2c9ab87846d
            algorithm = MessageDigest.getInstance("SHA");
            // 重置摘要以供再次使用
            algorithm.reset();
            // 使用bytes更新摘要
            algorithm.update(str.getBytes());
            // 使用指定的byte数组对摘要进行最后更新,然后完成摘要计算
            return toHexString(algorithm.digest(), "");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    // 将字符串中的每个字符转换为十六进制
    private static String toHexString(byte[] bytes, String separtor) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append("0");
            }
            hexString.append(hex).append(separtor);
        }
        return hexString.toString();
    }
}

对称加密算法 
同一个秘钥可以同时作为信息的加密和解密。 
DES(Data Encryption Standard)数据标准加密

public class DES {
    // 初始化向量,随意填充
    private static byte[] iv = { 'a', 'b', 'c', 'd', 'e', 1, 2, '*' };

    public static void main(String[] args) {
        // 指定密匙
        String key = "*()&^%$#";
        // 指定需要加密的明文
        String text = "4454069u =o 5h6u= bopregkljoj";
        try {
            // 调用DES加密方法
            String encryString = DES.encryptDES(text, key);
            System.out.println("DES加密结果: " + encryString);
            // 调用DES解密方法
            String decryString = DES.decryptDES(encryString, key);
            System.out.println("DES解密结果: " + decryString);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // DES加密
    // encryptText为原文
    // encryptKey为密匙
    private static String encryptDES(String encryptText, String encryptKey)
            throws Exception {
        // 实例化IvParameterSpec对象,使用指定的初始化向量
        IvParameterSpec spec = new IvParameterSpec(iv);
        // 实例化SecretKeySpec类,根据字节数组来构造SecretKeySpec
        SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
        // 创建密码器
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        // 用密码初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, key, spec);
        // 执行加密操作
        byte[] encryptData = cipher.doFinal(encryptText.getBytes());
        // 返回加密后的数据
        return Base64.getEncoder().encodeToString(encryptData);
    }

    // 解密
    private static String decryptDES(String decryptString, String decryptKey)
            throws Exception {
        // 先使用Base64解密
        byte[] base64byte = Base64.getDecoder().decode(decryptString);
        // 实例化IvParameterSpec对象,使用指定的初始化向量
        IvParameterSpec spec = new IvParameterSpec(iv);
        // 实例化SecretKeySpec类,根据字节数组来构造SecretKeySpec
        SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
        // 创建密码器
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        // 用密码初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, key, spec);
        // 获取解密后的数据
        byte decryptedData[] = cipher.doFinal(base64byte);
        // 将解密后数据转换为字符串输出
        return new String(decryptedData);
    }

}

AES(Advanced Encryption Standrad)高级加密标准

public class AES {

    public static void main(String[] args) throws Exception {
        // 设置加密密匙
        String masterPassword = "AndroidERHJ";
        // 设置原文
        String originalText = "ABCDEFGHIJKLMNOPQRS547KYU,N;[HTUVWXYZ";
        // 调用AES加密方法
        String encryptingCode = AES.encrypt(masterPassword, originalText);
        System.out.println("加密结果:" + encryptingCode);
        // 调用AES解密方法
        String decryString = AES.decrypt(masterPassword, encryptingCode);
        System.out.println("解密结果:" + decryString);
    }

    // AES加密
    // encryptText为要加密的内容
    // seed为密匙
    public static String encrypt(String seed, String encryptText)
            throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = encrypt(rawKey, encryptText.getBytes());
        return toHex(result);
    }

    // AES解密
    // decryptText为需要解密的内容
    // seed为密匙
    public static String decrypt(String seed, String decryptText)
            throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] enc = toByte(decryptText);
        byte[] result = decrypt(rawKey, enc);
        return new String(result);

    }

    // 加密
    private static byte[] encrypt(byte[] raw, byte[] bytes) throws Exception {
        // 生成一组扩展密匙,并放入一个数组之中
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        // 用ENCRYPT_MODE模式,用skeySpec密码组,生成AES加密方法
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        // 得到加密数据
        byte[] encrypted = cipher.doFinal(bytes);
        return encrypted;
    }

    // 解密
    private static byte[] decrypt(byte[] rawKey, byte[] enc) throws Exception {
        // 生成一组扩展密匙,并放入一个数组之中
        SecretKeySpec skeyKeySpec = new SecretKeySpec(rawKey, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        // 用DECRYPT_MODE模式,用skeySpec密码组,生成AES解密方法
        cipher.init(Cipher.DECRYPT_MODE, skeyKeySpec);
        // 得到解密数据
        byte[] decrypted = cipher.doFinal(enc);
        return decrypted;
    }

    // 对密匙进行编码
    private static byte[] getRawKey(byte[] bytes) throws Exception {
        // 获取密匙生成器
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(bytes);
        // 生成128位的AES密码生成器
        kgen.init(128, sr);
        // 生成密匙
        SecretKey sKey = kgen.generateKey();
        // 编码格式
        byte[] raw = sKey.getEncoded();
        return raw;
    }

    // 将十六进制字符串为十进制字符串
    private static String fromHex(String hex) {
        return new String(toByte(hex));
    }

    // 将十六进制字符串为十进制字节数组
    private static byte[] toByte(String hex) {
        int len = hex.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++) {
            result[i] = Integer.valueOf(hex.substring(2 * i, 2 * i + 2), 16)
                    .byteValue();
        }
        return result;
    }

    // 把一个十进制字节数组转换成十六进制
    private static String toHex(String txt) {
        return toHex(txt.getBytes());
    }

    // 把一个十进制字节数组转换成十六进制
    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 result, byte b) {
        result.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0X0f));

    }

}

非对称加密 
RSA加密:

public class RSA {

    public static void main(String[] args) {
        rsa();
    }

    private static String str = "姑娘,我爱你!";// 要加密的内容

    private static void rsa() {
        try {
            // 1.初始化秘钥
            KeyPairGenerator keyPairGenerator = KeyPairGenerator
                    .getInstance("RSA");
            // 设置长度,一定是64整倍数
            keyPairGenerator.initialize(512);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
            System.out.println("publicKey:"
                    + Base64.getEncoder().encodeToString(
                            rsaPublicKey.getEncoded()));
            System.out.println("privateKey:"
                    + Base64.getEncoder().encodeToString(
                            rsaPrivateKey.getEncoded()));
            // 2.私钥加密、 公钥解密--加密
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                    rsaPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory
                    .generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] result = cipher.doFinal(str.getBytes());
            System.out.println("私钥加密、 公钥解密--加密:"
                    + Base64.getEncoder().encodeToString(result));

            // 3.私钥加密、公钥解密--解密
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
                    rsaPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            result = cipher.doFinal(result);
            System.out.println("私钥加密、公钥解密--解密: " + new String(result));

            // 4.公钥加密、私钥解密--加密
            x509EncodedKeySpec = new X509EncodedKeySpec(
                    rsaPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("RSA");
            publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            result = cipher.doFinal(str.getBytes());
            System.out.println("公钥加密、私钥解密--加密: "
                    + Base64.getEncoder().encodeToString(result));

            // 5.公钥加密、私钥解密--解密
            pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                    rsaPrivateKey.getEncoded());
            keyFactory = KeyFactory.getInstance("RSA");
            privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            result = cipher.doFinal(result);
            System.out.println("公钥加密、私钥解密--解密: " + new String(result));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值