Android平台下的加密算法之(RSA/DES/AES)

来源:互联网 发布:知白新书 编辑:程序博客网 时间:2024/05/01 11:40

最近工作需要加密数据,在网上收集了一下加密算法,在此给刚接触安卓的朋友们介绍一下

首先是RSA加密:

import java.security.Key;    import java.security.KeyFactory;    import java.security.KeyPair;    import java.security.KeyPairGenerator;    import java.security.PrivateKey;    import java.security.PublicKey;    import java.security.interfaces.RSAPrivateKey;    import java.security.interfaces.RSAPublicKey;    import java.security.spec.PKCS8EncodedKeySpec;    import java.security.spec.X509EncodedKeySpec;         import javax.crypto.Cipher;    import android.util.Base64;     public class RSAHelper { public static PublicKey getPublicKey(String key) throws Exception {             byte[] keyBytes;            //keyBytes = (new BASE64Decoder()).decodeBuffer(key);          keyBytes= Base64.decode(key.getBytes(), Base64.DEFAULT);           X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);             KeyFactory keyFactory = KeyFactory.getInstance("RSA");             PublicKey publicKey = keyFactory.generatePublic(keySpec);             return publicKey;       }             public static PrivateKey getPrivateKey(String key) throws Exception {             byte[] keyBytes;             //keyBytes = (new BASE64Decoder()).decodeBuffer(key);             keyBytes= Base64.decode(key.getBytes(), Base64.DEFAULT);         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);             KeyFactory keyFactory = KeyFactory.getInstance("RSA");             PrivateKey privateKey = keyFactory.generatePrivate(keySpec);             return privateKey;       }               public static String getKeyString(Key key) throws Exception {             byte[] keyBytes = key.getEncoded();            /* String s = (new BASE64Encoder()).encode(keyBytes);             return s;   */                   return new String(Base64.encode(keyBytes, Base64.DEFAULT));   }           public static void main(byte[] args) throws Exception {               KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");             //密钥位数             keyPairGen.initialize(1024);             //密钥对             KeyPair keyPair = keyPairGen.generateKeyPair();               // 公钥             PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();               // 私钥             PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();               String publicKeyString = getKeyString(publicKey);             System.out.println("public:/n" + publicKeyString);               String privateKeyString = getKeyString(privateKey);             System.out.println("private:/n" + privateKeyString);               //加解密类             Cipher cipher = Cipher.getInstance("RSA");//Cipher.getInstance("RSA/ECB/PKCS1Padding");               //明文             byte[] plainText =args;               //加密             cipher.init(Cipher.ENCRYPT_MODE, publicKey);             byte[] enBytes = cipher.doFinal(plainText);               String es = new String(Base64.encode(enBytes, Base64.DEFAULT));             System.out.println(es);                  //通过密钥字符串得到密钥             publicKey = getPublicKey(publicKeyString);             privateKey = getPrivateKey(privateKeyString);               //解密             cipher.init(Cipher.DECRYPT_MODE, privateKey);             byte[]deBytes = cipher.doFinal(enBytes);               publicKeyString = getKeyString(publicKey);             System.out.println("public:/n" +publicKeyString);               privateKeyString = getKeyString(privateKey);             System.out.println("private:/n" + privateKeyString);               String s = new String(deBytes);             System.out.println(s);           } }

再者是DES加密:

import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import android.util.Base64;public  class DES {private static byte[] iv = {1,2,3,4,5,6,7,8}; public static String encryptDES(String encryptString, String encryptKey) throws Exception { IvParameterSpec zeroIv = new IvParameterSpec(iv); SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES"); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv); byte[] encryptedData = cipher.doFinal(encryptString.getBytes()); return new String(Base64.encode(encryptedData,Base64.DEFAULT)); } public static String decryptDES(String decryptString, String decryptKey) throws Exception { byte[] byteMi =  Base64.decode(decryptString,Base64.DEFAULT); IvParameterSpec zeroIv = new IvParameterSpec(iv); SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES"); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, zeroIv); byte decryptedData[] = cipher.doFinal(byteMi); String s= new String(decryptedData); return s;} }


 最后是AES加密:

import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;public class AES {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 {  // TODO Auto-generated method stub   KeyGenerator kgen = KeyGenerator.getInstance("AES");  SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");  sr.setSeed(seed);  kgen.init(128, sr);  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);  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);  byte[] decrypted = cipher.doFinal(encrypted);  return decrypted;  }  public static String toHex(String txt) {  return toHex(txt.getBytes());  }  public static String fromHex(String hex) {  return new String(toByte(hex));  }  public 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;  }  public 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 static void appendHex(StringBuffer sb, byte b) {  final String HEX = "0123456789ABCDEF";  sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));  }  }



 

0 0
原创粉丝点击