java – BASE64Encoder是内部API,可能会在将来的版本中删除

前端之家收集整理的这篇文章主要介绍了java – BASE64Encoder是内部API,可能会在将来的版本中删除前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > how to avoid warning for the Base 64?2个
我试图解决这个问题,但我从来没有找到适合我的解决方案.问题是我正在接受有关BASE64Encoder的警告.没有BASE64Encoder,有没有其他方法可以做到这一点?

代码

public static String Encrypt(String Data) throws Exception 
{
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.ENCRYPT_MODE,key);
    byte[] encVal = c.doFinal(Data.getBytes());
    String encryptedValue = new BASE64Encoder().encode(encVal); //Here is the problem

    return encryptedValue;
}

public static String Decrypt(String encryptedData) throws Exception 
{
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE,key);
    byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData); //Another problem
    byte[] decValue = c.doFinal(decordedValue);
    String decryptedValue = new String(decValue);

    return decryptedValue;
}

private static Key generateKey() throws Exception 
{
    Key key = new SecretKeySpec(keyValue,ALGO);
    return key;
}

解决方法

您现在应该使用Base64编码器和解码器类(从Java 8开始).

https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html

import java.util.Base64;
import java.util.UUID;
import java.io.UnsupportedEncodingException;

public class HelloWorld {
   public static void main(final String... args) {
      try {
         // Encode using basic encoder
         String base64encodedString = Base64.getEncoder().encodeToString("TutorialsPoint?java8".getBytes("utf-8"));
         System.out.println("Base64 Encoded String (Basic) :" + base64encodedString);

         // Decode
         byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);

         System.out.println("Original String: " + new String(base64decodedBytes,"utf-8"));
         base64encodedString = Base64.getUrlEncoder().encodeToString("TutorialsPoint?java8".getBytes("utf-8"));
         System.out.println("Base64 Encoded String (URL) :" + base64encodedString);

         StringBuilder stringBuilder = new StringBuilder();

         for (int i = 0; i < 10; ++i) {
            stringBuilder.append(UUID.randomUUID().toString());
         }

         byte[] mimeBytes = stringBuilder.toString().getBytes("utf-8");
         String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);
         System.out.println("Base64 Encoded String (MIME) :" + mimeEncodedString);

      } catch (UnsupportedEncodingException e) {
         System.out.println("Error :" + e.getMessage());
      }
   }
}

代码取自HERE.

原文链接:https://www.f2er.com/java/129549.html

猜你在找的Java相关文章