首页 > 系统 > 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. if (i == start + len - 2) { 
  47. int d = ((((int) data[i]) & 0x0ff) << 16) 
  48. | ((((int) data[i + 1]) & 255) << 8); 
  49. buf.append(legalChars[(d >> 18) & 63]); 
  50. buf.append(legalChars[(d >> 12) & 63]); 
  51. buf.append(legalChars[(d >> 6) & 63]); 
  52. buf.append("="); 
  53. else if (i == start + len - 1) { 
  54. int d = (((int) data[i]) & 0x0ff) << 16; 
  55. buf.append(legalChars[(d >> 18) & 63]); 
  56. buf.append(legalChars[(d >> 12) & 63]); 
  57. buf.append("=="); 
  58. return buf.toString(); 
  59. private static int decode(char c) { 
  60. if (c >= 'A' && c <= 'Z'
  61. return ((int) c) - 65; 
  62. else if (c >= 'a' && c <= 'z'
  63. return ((int) c) - 97 + 26; 
  64. else if (c >= '0' && c <= '9'
  65. return ((int) c) - 48 + 26 + 26; 
  66. else 
  67. switch (c) { 
  68. case '+'
  69. return 62; 
  70. case '/'
  71. return 63; 
  72. case '='
  73. return 0; 
  74. default
  75. throw new RuntimeException("unexpected code: " + c); 
  76. public static byte[] decode(String s) { 
  77. ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
  78. try { 
  79. decode(s, bos); 
  80. catch (IOException e) { 
  81. throw new RuntimeException(); 
  82. byte[] decodedBytes = bos.toByteArray(); 
  83. try { 
  84. bos.close(); 
  85. bos = null
  86. catch (IOException ex) { 
  87. System.err.println("Error while decoding BASE64: " + ex.toString()); 
  88. return decodedBytes; 
  89. private static void decode(String s, OutputStream os) throws IOException { 
  90. int i = 0; 
  91. int len = s.length(); 
  92. while (true) { 
  93. while (i < len && s.charAt(i) <= ' '
  94. i++; 
  95. if (i == len) 
  96. break
  97. int tri = (decode(s.charAt(i)) << 18) 
  98. + (decode(s.charAt(i + 1)) << 12) 
  99. + (decode(s.charAt(i + 2)) << 6) 
  100. + (decode(s.charAt(i + 3))); 
  101. os.write((tri >> 16) & 255); 
  102. if (s.charAt(i + 2) == '='
  103. break
  104. os.write((tri >> 8) & 255); 
  105. if (s.charAt(i + 3) == '='
  106. break
  107. os.write(tri & 255); 
  108. i += 4; 

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. public static String decrypt(String seed, String encrypted) 
  21. throws Exception { 
  22. byte[] rawKey = getRawKey(seed.getBytes()); 
  23. byte[] enc = toByte(encrypted); 
  24. byte[] result = decrypt(rawKey, enc); 
  25. return new String(result); 
  26. private static byte[] getRawKey(byte[] seed) throws Exception { 
  27. KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
  28. SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); 
  29. sr.setSeed(seed); 
  30. kgen.init(128, sr); // 192 and 256 bits may not be available 
  31. SecretKey skey = kgen.generateKey(); 
  32. byte[] raw = skey.getEncoded(); 
  33. return raw; 
  34. private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception { 
  35. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 
  36. Cipher cipher = Cipher.getInstance("AES"); 
  37. cipher.init(Cipher.ENCRYPT_MODE, skeySpec); 
  38. byte[] encrypted = cipher.doFinal(clear); 
  39. return encrypted; 
  40. private static byte[] decrypt(byte[] raw, byte[] encrypted) 
  41. throws Exception { 
  42. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 
  43. Cipher cipher = Cipher.getInstance("AES"); 
  44. cipher.init(Cipher.DECRYPT_MODE, skeySpec); 
  45. byte[] decrypted = cipher.doFinal(encrypted); 
  46. return decrypted; 
  47. public static String toHex(String txt) { 
  48. return toHex(txt.getBytes()); 
  49. public static String fromHex(String hex) { 
  50. return new String(toByte(hex)); 
  51. public static byte[] toByte(String hexString) { 
  52. int len = hexString.length() / 2; 
  53. byte[] result = new byte[len]; 
  54. for (int i = 0; i < len; i++) 
  55. result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 
  56. 16).byteValue(); 
  57. return result; 
  58. public static String toHex(byte[] buf) { 
  59. if (buf == null
  60. return ""
  61. StringBuffer result = new StringBuffer(2 * buf.length); 
  62. for (int i = 0; i < buf.length; i++) { 
  63. appendHex(result, buf[i]); 
  64. return result.toString(); 
  65. private static void appendHex(StringBuffer sb, byte b) { 
  66. sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f)); 

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. }  

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


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