美文网首页androidAndroid
android Base64 AES加密解密

android Base64 AES加密解密

作者: 大明白 | 来源:发表于2015-06-12 11:38 被阅读6202次

    Android Base64代码如下:

    // 加密传入的数据是byte类型的,并非使用decode方法将原始数据转二进制,String类型的数据 使用 str.getBytes()即可
    String str = "Hello!";
    // 在这里使用的是encode方式,返回的是byte类型加密数据,可使用new String转为String类型
    String strBase64 = new String(Base64.encode(str.getBytes(), Base64.DEFAULT));
    Log.i("Test", "encode >>>" + strBase64);
            
    // 这里 encodeToString 则直接将返回String类型的加密数据
    String enToStr = Base64.encodeToString(str.getBytes(), Base64.DEFAULT);
    Log.i("Test", "encodeToString >>> " + enToStr);
            
    // 对base64加密后的数据进行解密
    Log.i("Test", "decode >>>" + new String(Base64.decode(strBase64.getBytes(), Base64.DEFAULT)));
    

    Android AES代码如下:

    /**
      * @param
      * @return AES加密算法加密
      * @throws Exception
      */
     public static String encrypt(String seed, String cleartext)
       throws Exception {
      byte[] rawKey = getRawKey(seed.getBytes());
      byte[] result = encrypt(rawKey, cleartext.getBytes());
      return toHex(result);
     }
     /**
      * @param
      * @return AES加密算法加密
      * @throws Exception
      */
     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 String toHex(byte[] buf) {
      final String HEX = "0123456789ABCDEF";
      if (buf == null)
       return "";
      StringBuffer result = new StringBuffer(2 * buf.length);
      for (int i = 0; i < buf.length; i++) {
       result.append(HEX.charAt((buf[i] >> 4) & 0x0f)).append(
         HEX.charAt(buf[i] & 0x0f));
      }
      return result.toString();
     }
     /**
      * @param raw
      * @param encrypted
      * @return AES加密算法解密
      * @throws Exception
      */
     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[] 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;
     }
     private 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;
     }
     private static byte[] getRawKey(byte[] seed) throws Exception {
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
      sr.setSeed(seed);
      kgen.init(128, sr); // 192 and 256 bits may not be available
      SecretKey skey = kgen.generateKey();
      byte[] raw = skey.getEncoded();
      return raw;
     }
    
    // 使用该方法
    String masterPassword = "test";    
    String originalText = "0123456789";  
    String encryptingCode = SimpleCrypto.encrypt(masterPassword,originalText);    
    Log.i("加密结果为 ",encryptingCode);    
    String decryptingCode = SimpleCrypto.decrypt(masterPassword, encryptingCode);  
    Log.i("解密结果",decryptingCode);

    相关文章

      网友评论

      • denglxsc:android base64 方法不行的,如下:
        Exception in thread "main" java.lang.RuntimeException: Stub!
        at android.util.Base64.encode(Base64.java:26)

        目前测试几种方案中只有通过反射方法可以,不知为何,大佬可有解决方案?
      • zxbin:可以运行。:+1:
      • d5962134cef8:SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); 要不然解密的时候会报错javax.crypto.BadPaddingException: pad block corrupted.
        大明白:@小古攀花 文章里的代码已经修改了的。
        小古攀花:这句代码加到哪里
        大明白:谢谢,方法比较老。没有更新,造成困扰望谅解!
      • La0s:using Base64.DEFAULT will insert a line break in my case. I use Base64.NO_WRAP instead

      本文标题:android Base64 AES加密解密

      本文链接:https://www.haomeiwen.com/subject/vkvjqttx.html