android加密、签名相关

此文重在思路梳理

加密方法部分:

  1. 代码加密方式—— SHA1:
   //SHA1 加密实例,info可以是keystore或jks文件中的内容
  public static String encryptToSHA(String info) {
    byte[] digesta = null;
    try {
      // 得到一个SHA-1的消息摘要
      MessageDigest alga = MessageDigest.getInstance("SHA-1");
      // 添加要进行计算摘要的信息
      alga.update(info.getBytes());
      // 得到该摘要
      digesta = alga.digest();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    // 将摘要转为字符串
    String rs = byte2hex(digesta);
    return rs + key;
  }

  public String byte2hex(byte[] b){
    String hs="";
    String stmp="";
    for (int n=0;n<b.length;n++){
    stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
    if (stmp.length()==1) hs=hs+"0"+stmp;
    else hs=hs+stmp;.
    if (n<b.length-1) hs=hs+"%";
    }
    return hs.toUpperCase();
 }

2 . 代码加密方式 —— RSA:

public class RSA_Encrypt {
/** 指定加密算法为DESede */
private static String ALGORITHM = "RSA";
/** 指定key的大小 */
private static int KEYSIZE = 1024;
/** 指定公钥存放文件 */
private static String PUBLIC_KEY_FILE = "PublicKey";
/** 指定私钥存放文件 */
private static String PRIVATE_KEY_FILE = "PrivateKey";

/**
* 生成密钥对
*/
private static void generateKeyPair() throws Exception{
  /** RSA算法要求有一个可信任的随机数源 */
   SecureRandom sr = new SecureRandom();
   /** 为RSA算法创建一个KeyPairGenerator对象 */
   KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
  /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
   kpg.initialize(KEYSIZE, sr);
   /** 生成密匙对 */
   KeyPair kp = kpg.generateKeyPair();
   /** 得到公钥 */
   Key publicKey = kp.getPublic();
   /** 得到私钥 */
   Key privateKey = kp.getPrivate();
   /** 用对象流将生成的密钥写入文件 */
   ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
   ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
   oos1.writeObject(publicKey);
   oos2.writeObject(privateKey);
   /** 清空缓存,关闭文件输出流 */
   oos1.close();
   oos2.close();
}

/**
* 加密方法
* source: 源数据
*/
public static String encrypt(String source) throws Exception{
   generateKeyPair();
   /** 将文件中的公钥对象读出 */
   ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
   Key key = (Key) ois.readObject();
   ois.close();
   /** 得到Cipher对象来实现对源数据的RSA加密 */
   Cipher cipher = Cipher.getInstance(ALGORITHM);
   cipher.init(Cipher.ENCRYPT_MODE, key);
   byte[] b = source.getBytes();
   /** 执行加密操作 */
   byte[] b1 = cipher.doFinal(b);
   BASE64Encoder encoder = new BASE64Encoder();
   return encoder.encode(b1);
}

/**
* 解密算法
* cryptograph:密文
*/
public static String decrypt(String cryptograph) throws Exception{
   /** 将文件中的私钥对象读出 */
   ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
   Key key = (Key) ois.readObject();
   /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
   Cipher cipher = Cipher.getInstance(ALGORITHM);
   cipher.init(Cipher.DECRYPT_MODE, key);
   BASE64Decoder decoder = new BASE64Decoder();
   byte[] b1 = decoder.decodeBuffer(cryptograph);
   /** 执行解密操作 */
   byte[] b = cipher.doFinal(b1);
   return new String(b);
}
public static void main(String[] args) throws Exception {
   String source = "Hello World!";//要加密的字符串
   String cryptograph = encrypt(source);//生成的密文
   System.out.println(cryptograph);

   String target = decrypt(cryptograph);//解密密文

3 . 利用工具生成RSA秘钥对:

准备工作:需要先安装git。
然后用GitBash创建SSH的RSA秘钥对:点开git->Git Bash输入: ssh-keygen -t rsa –C “youremail@example.com”
(提示:两个非对称秘钥生成的文件在C:\Users\Administrator.ssh)


查看签名文件加密方式信息:

提示:debug和Release的keystore(或.jks文件)是不同的,但若使用同一个.jks或同keystore的话,里边的sha1是相同的,也就是说keystore其实就是已经经过sha1和RSA加密过的文件了,如何查看看下边:

查看debug和release模式下,两种被加密过的”签名文件“中加密信息:

在dos或Terminal中的输入(jdk中的keytool)命令:
keytool -v -list -keystore keytool -v -list -keystore C:\Users\Administrator.5PCBYL0J8BSDL0C.android.debug.keystore\keystore绝对路径,或直接进入到目录下在进入CMD或Terminal中执行:
keytool -v -list -keystore debug.keystore

(提示:AndroidStudio的debug模式下的debug.keystore默认位置类似在C:\Users\Administrator.5PCBYL0J8BSDL0C.android 这里,密码都为android,别名为androiddebugkey )


生成签名文件:

studio界面方式:
Build->Generate Signed APK 然后一步步地我们自主生成

CMD命令方式:
1、打开CMD进入Java\jdk1.7.0_03\bin文件夹(即jdk的bin目录下找到keytool.exe)
2、根据以下命令输入:

keytool -genkey -alias androiddebugkey -keyalg RSA -validity 20000 -keystore debug.keystore -storepass android -keypass android
(之后按照说明输入即可 )


打包部分:

在用release.jks打包release发布版本的apk时报错:Android xxx is not translated in zh解决办法:

android {
    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }
}

但是当我们打包debug测试版本的apk时,则不会报这个错误,因为它不会进行这样的严格检查,以便加快速度;

了解更多加密方案:那就点我吧!

RSA封装类 ,完整的RSA加密和解密 public class RSAUtilEncrypt { public static final String KEY_ALGORTHM = "RSA";// public static final String KEY_ALGORTHM_RSA_ECB_PKCS1PADDING = "RSA/ECB/PKCS1Padding"; public static String RSA_PUBLIC_KEY = "rsa_public_key"; public static String RSA_PRIVATE_KEY = "rsa_private_key"; private int KeySize = 1024; private Map keyMap; private static String RSA = "RSA"; private static PublicKey publickey; public RSAUtilEncrypt(int KeySize,String publickey) { this.KeySize = KeySize; try { this.publickey=generatePublicKeyByString(publickey); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private RSAPublicKey generatePublicKeyByString(String publicKeyStr) throws Exception { try { BASE64Decoder base64Decoder = new BASE64Decoder(); byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("No Algorthm,Checked by cemung!"); } catch (InvalidKeySpecException e) { throw new Exception("InvalidKeySpec!"); } catch (IOException e) { throw new Exception("Io exception!"); } catch (NullPointerException e) { throw new Exception("Illegle pointer reference!"); } } // Encypt public byte[] RSAEncrypt(byte[] data, RSAPublicKey publickey) throws Exception { Cipher cipher = Cipher.getInstance(KEY_ALGORTHM_RSA_ECB_PKCS1PADDING); cipher.init(Cipher.ENCRYPT_MODE, this.publickey); byte[] cipherbytes = cipher.doFinal(data); return cipherbytes; } // Encypt public byte[] RSAEncrypt(byte[] data) throws Exception { Cipher cipher = Cipher.getInstance(KEY_ALGORTHM_RSA_ECB_PKCS1PADDING); cipher.init(Cipher.ENCRYPT_MODE, this.publickey); byte[] cipherbytes = cipher.doFinal(data); return cipherbytes; } // Get Public key with format byte[] public byte[] getPublicKeyByte() { RSAPublicKey pubkey = (RSAPublicKey) keyMap.get(RSA_PUBLIC_KEY); return pubkey.getEncoded(); } public static byte[] decryptBASE64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key); } public static String encryptBASE64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key); } public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); } public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); } public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicKey); return cipher.doFinal(data); } 使用方法 private RSAUtilEncrypt rsa = new RSAUtilEncrypt(1024, publikey); /* * 给信息加密,获取密文 */ public String getCiphertext(String str_encrode) { try { byte[] estr = rsa.RSAEncrypt(str_encrode.getBytes()); // 密文 String ciphertext = Base64.encodeToString(estr, Base64.DEFAULT); return ciphertext; } catch (Exception e) { e.printStackTrace(); } return null; } 有疑问的留言
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值