android学习笔记之DES_加密解密

  • 格式:doc
  • 大小:51.00 KB
  • 文档页数:8

DES加密算法调用DES加密算法包最精要的就是下面两句话:Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);CBC是工作模式,DES一共有电子密码本模式(ECB)、加密分组链接模式(CBC)、加密反馈模式(CFB)和输出反馈模式(OFB)四种模式,PKCS5Padding是填充模式,还有其它的填充模式:然后,cipher.init()一共有三个参数:Cipher.ENCRYPT_MODE, key, zeroIv,zeroIv就是初始化向量,一个8为字符数组。

工作模式、填充模式、初始化向量这三种因素一个都不能少。

否则,如果你不指定的话,那么就要程序就要调用默认实现。

一般情况下,加密后的结果都会用base64编码进行传输。

java平台:主程序1.public class testDES {2.3./**4.* @param args5.* @throws Exception6.*/7.public static void main(String[] args) throws Exception {8.// TODO Auto-generated method stub9.String key = "12345678";10. String text = "12345678";11. String result1 = DES.encryptDES(text,key);12. String result2 = DES.decryptDES(result1, key);13. System.out.println(result1);14. System.out.println(result2);15. }16.}用到的DES加密类1.import javax.crypto.Cipher;2.import javax.crypto.spec.IvParameterSpec;3.import javax.crypto.spec.SecretKeySpec;1.public class DES {2.private static byte[] iv = {1,2,3,4,5,6,7,8};3.public static String encryptDES(String encryptString, String encryptKey) throws Exception {4.// IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);5.IvParameterSpec zeroIv = new IvParameterSpec(iv);6.SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");7.Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");8.cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);9.byte[] encryptedData = cipher.doFinal(encryptString.getBytes());10.11. return Base64.encode(encryptedData);12. }13. public static String decryptDES(String decryptString, String decryptKey) throws Exception {14. byte[] byteMi = new Base64().decode(decryptString);15. IvParameterSpec zeroIv = new IvParameterSpec(iv);16.// IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);17. SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");18. Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");19. cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);20. byte decryptedData[] = cipher.doFinal(byteMi);21.22. return new String(decryptedData);23. }24.}××××××××××××××××××××××××××××××××××××××××用到的BASE64工具类:1.import java.io.ByteArrayOutputStream;2.import java.io.IOException;3.import java.io.OutputStream;4.5.6.7.public class Base64 {8.private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCh arArray();9./**10.* data[]进行编码11.* @param data12.* @return13.*/14. public static String encode(byte[] data) {15. int start = 0;16. int len = data.length;17. StringBuffer buf = new StringBuffer(data.length * 3/ 2);18.19. int end = len - 3;20. int i = start;21. int n = 0;22.23. while(i <= end) {24. int d = ((((int) data[i])& 0x0ff) << 16)25. | ((((int) data[i + 1]) & 0x0ff) << 8)26. | (((int) data[i + 2]) & 0x0ff);27.28. buf.append(legalChars[(d >> 18) & 63]);29. buf.append(legalChars[(d >> 12) & 63]);30. buf.append(legalChars[(d >> 6) & 63]);31. buf.append(legalChars[d & 63]);32.33. i += 3;34.35. if(n++ >= 14) {36. n = 0;37. buf.append(" ");38. }39. }40.41. if(i == start + len - 2) {42. int d = ((((int) data[i])& 0x0ff) << 16)43. | ((((int) data[i + 1]) & 255) << 8);44.45. buf.append(legalChars[(d >> 18) & 63]);46. buf.append(legalChars[(d >> 12) & 63]);47. buf.append(legalChars[(d >> 6) & 63]);48. buf.append("=");49. } else if(i == start + len -1) {50. int d = (((int) data[i]) &0x0ff) << 16;51.52. buf.append(legalChars[(d >> 18) & 63]);53. buf.append(legalChars[(d >> 12) & 63]);54. buf.append("==");55. }56.57. return buf.toString();58. }59.60. private static int decode(char c) {61. if(c >= 'A'&& c <= 'Z')62. return((int) c) - 65;63. else if(c >= 'a'&& c <= 'z')64. return((int) c) - 97+ 26;65. else if(c >= '0'&& c <= '9')66. return((int) c) - 48+ 26+ 26;67. else68. switch(c) {69. case'+':70. return62;71. case'/':72. return63;73. case'=':74. return0;75. default:76. throw new RuntimeException("unexpected code: "+ c);77. }78. }79.80. /**81.* Decodes the given Base64 encoded String to a new byte array. The byte82.* array holding the decoded data is returned.83.*/84.85. public static byte[] decode(String s) {86.87. ByteArrayOutputStream bos = new ByteArrayOutputStream();88. try{89. decode(s, bos);90. } catch(IOException e) {91. throw new RuntimeException();92. }93. byte[] decodedBytes = bos.toByteArray();94. try{95. bos.close();96. bos = null;97. } catch(IOException ex) {98. System.err.println("Error while decoding BASE64: "+ ex.toString());99. }100.return decodedBytes;101.}102.103.private static void decode(String s, OutputStream os) throws IOException {104.int i = 0;105.106.int len = s.length();107.108.while(true) {109.while(i < len && s.c harAt(i) <= ' ')110.i++;111.112.if(i == len)113.break;114.115.int tri = (decode(s.cha rAt(i)) << 18)116.+ (decode (s.charAt(i + 1)) << 12)117.+ (decode (s.charAt(i + 2)) << 6)118.+ (decode (s.charAt(i + 3)));119.120.os.write((tri >> 16) & 255);121.if(s.charAt(i + 2) == '=')122.break;123.os.write((tri >> 8) & 255);124.if(s.charAt(i + 3) == '=')125.break;126.os.write(tri & 255);127.128.i += 4;129.}130.}131.132.}×××××××××××××××××××××××××××××××adnroid平台的主函数:1.public class main extends Activity {2./** Called when the activity is first created.*/3.@Override4.public void onCreate(Bundle savedInstanceState) {5.super.onCreate(savedInstanceState);6.setContentView(yout.main);7.8.String key = "12345678";9.String text = "12345678";10.11.12. try{13. String result1 = DES.encryptDES(text,key);14. String result2 = DES.decryptDES(result1, key);15. Log.i("DES encode text is ", result1);16. Log.i("DES encode text is ", result2);17. } catch(Exception e) {18. // TODO Auto-generated catch block19. e.printStackTrace();20. }21. }22.}。