首页 > 系统 > Android > 正文

Android编程加密算法小结(AES、Base64、RAS加密算法)

2019-10-24 20:33:36
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了Android编程加密算法,结合实例分析了AES、Base64及RAS加密算法,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例总结了Android编程加密算法。分享给大家供大家参考,具体如下:

android常用加密算法之Base64加密算法:

 

 
  1. package com.long; 
  2. /** 
  3. * Copyright (C) 2010 The Android Open Source Project 
  4. * 
  5. * Licensed under the Apache License, Version 2.0 (the "License"); 
  6. * you may not use this file except in compliance with the License. 
  7. * You may obtain a copy of the License at 
  8. * 
  9. * http://www.apache.org/licenses/LICENSE-2.0 
  10. * 
  11. * Unless required by applicable law or agreed to in writing, software 
  12. * distributed under the License is distributed on an "AS IS" BASIS, 
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  14. * See the License for the specific language governing permissions and 
  15. * limitations under the License. 
  16. */ 
  17. import java.io.ByteArrayOutputStream; 
  18. import java.io.IOException; 
  19. import java.io.OutputStream; 
  20. /* 
  21. * @author long 
  22. * 
  23. */ 
  24. public class Base64 { 
  25. private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" 
  26. .toCharArray(); 
  27. public static String encode(byte[] data) { 
  28. int start = 0; 
  29. int len = data.length; 
  30. StringBuffer buf = new StringBuffer(data.length * 3 / 2); 
  31. int end = len - 3; 
  32. int i = start; 
  33. int n = 0; 
  34. while (i <= end) { 
  35. int d = ((((int) data[i]) & 0x0ff) << 16) 
  36. | ((((int) data[i + 1]) & 0x0ff) << 8) 
  37. | (((int) data[i + 2]) & 0x0ff); 
  38. buf.append(legalChars[(d >> 18) & 63]); 
  39. buf.append(legalChars[(d >> 12) & 63]); 
  40. buf.append(legalChars[(d >> 6) & 63]); 
  41. buf.append(legalChars[d & 63]); 
  42. i += 3; 
  43. if (n++ >= 14) { 
  44. n = 0; 
  45. buf.append(" "); 
  46. } 
  47. } 
  48. if (i == start + len - 2) { 
  49. int d = ((((int) data[i]) & 0x0ff) << 16) 
  50. | ((((int) data[i + 1]) & 255) << 8); 
  51. buf.append(legalChars[(d >> 18) & 63]); 
  52. buf.append(legalChars[(d >> 12) & 63]); 
  53. buf.append(legalChars[(d >> 6) & 63]); 
  54. buf.append("="); 
  55. } else if (i == start + len - 1) { 
  56. int d = (((int) data[i]) & 0x0ff) << 16; 
  57. buf.append(legalChars[(d >> 18) & 63]); 
  58. buf.append(legalChars[(d >> 12) & 63]); 
  59. buf.append("=="); 
  60. } 
  61. return buf.toString(); 
  62. } 
  63. private static int decode(char c) { 
  64. if (c >= 'A' && c <= 'Z') 
  65. return ((int) c) - 65; 
  66. else if (c >= 'a' && c <= 'z') 
  67. return ((int) c) - 97 + 26; 
  68. else if (c >= '0' && c <= '9') 
  69. return ((int) c) - 48 + 26 + 26; 
  70. else 
  71. switch (c) { 
  72. case '+': 
  73. return 62; 
  74. case '/': 
  75. return 63; 
  76. case '=': 
  77. return 0; 
  78. default: 
  79. throw new RuntimeException("unexpected code: " + c); 
  80. } 
  81. } 
  82. public static byte[] decode(String s) { 
  83. ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
  84. try { 
  85. decode(s, bos); 
  86. } catch (IOException e) { 
  87. throw new RuntimeException(); 
  88. } 
  89. byte[] decodedBytes = bos.toByteArray(); 
  90. try { 
  91. bos.close(); 
  92. bos = null; 
  93. } catch (IOException ex) { 
  94. System.err.println("Error while decoding BASE64: " + ex.toString()); 
  95. } 
  96. return decodedBytes; 
  97. } 
  98. private static void decode(String s, OutputStream os) throws IOException { 
  99. int i = 0; 
  100. int len = s.length(); 
  101. while (true) { 
  102. while (i < len && s.charAt(i) <= ' ') 
  103. i++; 
  104. if (i == len) 
  105. break; 
  106. int tri = (decode(s.charAt(i)) << 18) 
  107. + (decode(s.charAt(i + 1)) << 12) 
  108. + (decode(s.charAt(i + 2)) << 6) 
  109. + (decode(s.charAt(i + 3))); 
  110. os.write((tri >> 16) & 255); 
  111. if (s.charAt(i + 2) == '=') 
  112. break; 
  113. os.write((tri >> 8) & 255); 
  114. if (s.charAt(i + 3) == '=') 
  115. break; 
  116. os.write(tri & 255); 
  117. i += 4; 
  118. } 
  119. } 
  120. } 

android常用加密算法之AES加密算法:

 

 
  1. package com.long; 
  2. import java.security.SecureRandom; 
  3. import javax.crypto.Cipher; 
  4. import javax.crypto.KeyGenerator; 
  5. import javax.crypto.SecretKey; 
  6. import javax.crypto.spec.SecretKeySpec; 
  7. /** 
  8. * AES加密解密算法 
  9. *  
  10. * @author long 
  11. *  
  12. */ 
  13. public class Encryption { 
  14. private final static String HEX = "0123456789ABCDEF"; 
  15. public static String encrypt(String seed, String cleartext) 
  16. throws Exception { 
  17. byte[] rawKey = getRawKey(seed.getBytes()); 
  18. byte[] result = encrypt(rawKey, cleartext.getBytes()); 
  19. return toHex(result); 
  20. } 
  21. public static String decrypt(String seed, String encrypted) 
  22. throws Exception { 
  23. byte[] rawKey = getRawKey(seed.getBytes()); 
  24. byte[] enc = toByte(encrypted); 
  25. byte[] result = decrypt(rawKey, enc); 
  26. return new String(result); 
  27. } 
  28. private static byte[] getRawKey(byte[] seed) throws Exception { 
  29. KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
  30. SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); 
  31. sr.setSeed(seed); 
  32. kgen.init(128, sr); // 192 and 256 bits may not be available 
  33. SecretKey skey = kgen.generateKey(); 
  34. byte[] raw = skey.getEncoded(); 
  35. return raw; 
  36. } 
  37. private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception { 
  38. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 
  39. Cipher cipher = Cipher.getInstance("AES"); 
  40. cipher.init(Cipher.ENCRYPT_MODE, skeySpec); 
  41. byte[] encrypted = cipher.doFinal(clear); 
  42. return encrypted; 
  43. } 
  44. private static byte[] decrypt(byte[] raw, byte[] encrypted) 
  45. throws Exception { 
  46. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 
  47. Cipher cipher = Cipher.getInstance("AES"); 
  48. cipher.init(Cipher.DECRYPT_MODE, skeySpec); 
  49. byte[] decrypted = cipher.doFinal(encrypted); 
  50. return decrypted; 
  51. } 
  52. public static String toHex(String txt) { 
  53. return toHex(txt.getBytes()); 
  54. } 
  55. public static String fromHex(String hex) { 
  56. return new String(toByte(hex)); 
  57. } 
  58. public static byte[] toByte(String hexString) { 
  59. int len = hexString.length() / 2; 
  60. byte[] result = new byte[len]; 
  61. for (int i = 0; i < len; i++) 
  62. result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 
  63. 16).byteValue(); 
  64. return result; 
  65. } 
  66. public static String toHex(byte[] buf) { 
  67. if (buf == null) 
  68. return ""; 
  69. StringBuffer result = new StringBuffer(2 * buf.length); 
  70. for (int i = 0; i < buf.length; i++) { 
  71. appendHex(result, buf[i]); 
  72. } 
  73. return result.toString(); 
  74. } 
  75. private static void appendHex(StringBuffer sb, byte b) { 
  76. sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f)); 
  77. } 
  78. } 

Android常用加密算法之RAS加密算法:

 

 
  1. import java.security.Key;  
  2. import java.security.KeyFactory;  
  3. import java.security.KeyPair;  
  4. import java.security.KeyPairGenerator;  
  5. import java.security.PrivateKey;  
  6. import java.security.PublicKey;  
  7. import java.security.interfaces.RSAPrivateKey;  
  8. import java.security.interfaces.RSAPublicKey;  
  9. import java.security.spec.PKCS8EncodedKeySpec;  
  10. import java.security.spec.X509EncodedKeySpec;  
  11. import javax.crypto.Cipher;  
  12. import sun.misc.BASE64Decoder;  
  13. import sun.misc.BASE64Encoder;  
  14. public class RSAHelper {  
  15. public static PublicKey getPublicKey(String key) throws Exception {  
  16. byte[] keyBytes;  
  17. keyBytes = (new BASE64Decoder()).decodeBuffer(key);  
  18. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  
  19. KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
  20. PublicKey publicKey = keyFactory.generatePublic(keySpec);  
  21. return publicKey;  
  22. }  
  23. public static PrivateKey getPrivateKey(String key) throws Exception {  
  24. byte[] keyBytes;  
  25. keyBytes = (new BASE64Decoder()).decodeBuffer(key);  
  26. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);  
  27. KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
  28. PrivateKey privateKey = keyFactory.generatePrivate(keySpec);  
  29. return privateKey;  
  30. }  
  31. public static String getKeyString(Key key) throws Exception {  
  32. byte[] keyBytes = key.getEncoded();  
  33. String s = (new BASE64Encoder()).encode(keyBytes);  
  34. return s;  
  35. }  
  36. public static void main(String[] args) throws Exception {  
  37. KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");  
  38. //密钥位数  
  39. keyPairGen.initialize(1024);  
  40. //密钥对  
  41. KeyPair keyPair = keyPairGen.generateKeyPair();  
  42. // 公钥  
  43. PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
  44. // 私钥  
  45. PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
  46. String publicKeyString = getKeyString(publicKey);  
  47. System.out.println("public:/n" + publicKeyString);  
  48. String privateKeyString = getKeyString(privateKey);  
  49. System.out.println("private:/n" + privateKeyString);  
  50. //加解密类  
  51. Cipher cipher = Cipher.getInstance("RSA");//Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  52. //明文  
  53. byte[] plainText = "我们都很好!邮件:@sina.com".getBytes();  
  54. //加密  
  55. cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
  56. byte[] enBytes = cipher.doFinal(plainText);  
  57. //通过密钥字符串得到密钥  
  58. publicKey = getPublicKey(publicKeyString);  
  59. privateKey = getPrivateKey(privateKeyString);  
  60. //解密  
  61. cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  62. byte[]deBytes = cipher.doFinal(enBytes);  
  63. publicKeyString = getKeyString(publicKey);  
  64. System.out.println("public:/n" +publicKeyString);  
  65. privateKeyString = getKeyString(privateKey);  
  66. System.out.println("private:/n" + privateKeyString);  
  67. String s = new String(deBytes);  
  68. System.out.println(s);  
  69. }  
  70. } 

希望本文所述对大家Android程序设计有所帮助。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表