programing

Base64를 사용하여 Base64에서 문자열을 디코딩하고 인코딩하는 방법을 아는 사람이 있습니까?

minimums 2023. 8. 6. 09:56
반응형

Base64를 사용하여 Base64에서 문자열을 디코딩하고 인코딩하는 방법을 아는 사람이 있습니까?

저는 다음 코드를 사용하고 있지만 작동하지 않습니다.

String source = "password"; 
byte[] byteArray = source.getBytes("UTF-16"); 
Base64 bs = new Base64(); 
//bs.encodeBytes(byteArray); 
System.out.println(bs.encodeBytes(byteArray)); 
//bs.decode(bs.encodeBytes(byteArray));
System.out.println(bs.decode(bs.encodeBytes(byteArray)));

첫 번째:

  • 인코딩을 선택합니다.UTF-8은 일반적으로 좋은 선택입니다. 양쪽 모두에서 확실히 유효한 인코딩을 고수하십시오.UTF-8이나 UTF-16이 아닌 다른 것을 사용하는 경우는 드물 것입니다.

전송 종료:

  • 문자열을 바이트로 인코딩합니다(예:text.getBytes(encodingName))
  • 다음을 사용하여 바이트를 base64로 인코딩합니다.Base64학급
  • 베이스64 전송

입고 종료:

  • base64를 수신합니다.
  • 다음을 사용하여 base64를 바이트로 디코딩합니다.Base64학급
  • 바이트를 문자열로 디코딩합니다(예:new String(bytes, encodingName))

그래서 다음과 같은 것이 있습니다.

// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");

또는 함께StandardCharsets:

// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);

Kotlimb이 이 기능을 더 잘 사용하려면 다음과 같이 하십시오.

fun String.decode(): String {
    return Base64.decode(this, Base64.DEFAULT).toString(charset("UTF-8"))
}

fun String.encode(): String {
    return Base64.encodeToString(this.toByteArray(charset("UTF-8")), Base64.DEFAULT)
}

예:

Log.d("LOGIN", "TEST")
Log.d("LOGIN", "TEST".encode())
Log.d("LOGIN", "TEST".encode().decode())

로 인코딩된 문자열을 디코딩하는 방법에 대한 정보를 검색하다가 여기에 오게 된 다른 사람에게.Base64.encodeBytes()제 해결책은 이렇습니다.

// encode
String ps = "techPass";
String tmp = Base64.encodeBytes(ps.getBytes());

// decode
String ps2 = "dGVjaFBhC3M=";
byte[] tmp2 = Base64.decode(ps2); 
String val2 = new String(tmp2, "UTF-8"); 

또한 이전 버전의 Android를 지원하기 때문에 http://iharder.net/base64 의 Robert Harder의 Base64 라이브러리를 사용하고 있습니다.

코틀린을 사용하는 경우 이렇게 사용하는 것보다

인코딩용

val password = "Here Your String"
val data = password.toByteArray(charset("UTF-8"))
val base64 = Base64.encodeToString(data, Base64.DEFAULT)

디코딩용

val datasd = Base64.decode(base64, Base64.DEFAULT)
val text = String(datasd, charset("UTF-8"))

비슷한 것

String source = "password"; 
byte[] byteArray;
try {
    byteArray = source.getBytes("UTF-16");
    System.out.println(new String(Base64.decode(Base64.encode(byteArray,
           Base64.DEFAULT), Base64.DEFAULT)));
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

암호화 방법:

byte[] encrpt= text.getBytes("UTF-8");
String base64 = Base64.encodeToString(encrpt, Base64.DEFAULT);

암호 해독 방법:

byte[] decrypt= Base64.decode(base64, Base64.DEFAULT);
String text = new String(decrypt, "UTF-8");

'1987.1987년.Base64' 클래스는 Base64 형식으로 정보를 인코딩하고 디코딩하는 기능을 제공합니다.

Base64 인코더를 얻는 방법?

Encoder encoder = Base64.getEncoder();

Base64 디코더를 얻는 방법?

Decoder decoder = Base64.getDecoder();

데이터를 인코딩하는 방법은 무엇입니까?

Encoder encoder = Base64.getEncoder();
String originalData = "java";
byte[] encodedBytes = encoder.encode(originalData.getBytes());

데이터를 디코딩하는 방법은 무엇입니까?

Decoder decoder = Base64.getDecoder();
byte[] decodedBytes = decoder.decode(encodedBytes);
String decodedStr = new String(decodedBytes);

자세한 내용은 이 링크에서 확인하실 수 있습니다.

위에 나와 맞지 않는 많은 답변들과 그 중 일부는 올바른 방식으로 예외 없이 처리됩니다.여기에 저에게도 놀라운 효과가 있는 완벽한 솔루션을 추가합니다.

//base64 decode string 
 String s = "ewoic2VydmVyIjoic2cuenhjLmx1IiwKInNuaSI6InRlc3RpbmciLAoidXNlcm5hbWUiOiJ0ZXN0
    ZXIiLAoicGFzc3dvcmQiOiJ0ZXN0ZXIiLAoicG9ydCI6IjQ0MyIKfQ==";
    String val = a(s) ;
     Toast.makeText(this, ""+val, Toast.LENGTH_SHORT).show();
    
       public static String a(String str) {
             try {
                 return new String(Base64.decode(str, 0), "UTF-8");
             } catch (UnsupportedEncodingException | IllegalArgumentException unused) {
                 return "This is not a base64 data";
             }
         }

이전 답변을 바탕으로 누군가가 사용하기를 원할 경우에 대비하여 다음과 같은 유틸리티 방법을 사용하고 있습니다.

    /**
 * @param message the message to be encoded
 *
 * @return the enooded from of the message
 */
public static String toBase64(String message) {
    byte[] data;
    try {
        data = message.getBytes("UTF-8");
        String base64Sms = Base64.encodeToString(data, Base64.DEFAULT);
        return base64Sms;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

/**
 * @param message the encoded message
 *
 * @return the decoded message
 */
public static String fromBase64(String message) {
    byte[] data = Base64.decode(message, Base64.DEFAULT);
    try {
        return new String(data, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

API 레벨 26 이상의 경우

String encodedString = Base64.getEncoder().encodeToString(byteArray);

참조: https://developer.android.com/reference/java/util/Base64.Encoder.html#encodeToString(byte []

2021년부터 코틀린에서 답변합니다.

인코딩:

val data: String = "Hello"
val dataByteArray: ByteArray = data.toByteArray()
val dataInBase64: String = Base64Utils.encode(dataByteArray)

디코딩:

val dataInBase64: String = "..."
val dataByteArray: ByteArray = Base64Utils.decode(dataInBase64)
val data: String = dataByteArray.toString()
package net.itempire.virtualapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class BaseActivity extends AppCompatActivity {
EditText editText;
TextView textView;
TextView textView2;
TextView textView3;
TextView textView4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        editText=(EditText)findViewById(R.id.edt);
        textView=(TextView) findViewById(R.id.tv1);
        textView2=(TextView) findViewById(R.id.tv2);
        textView3=(TextView) findViewById(R.id.tv3);
        textView4=(TextView) findViewById(R.id.tv4);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             textView2.setText(Base64.encodeToString(editText.getText().toString().getBytes(),Base64.DEFAULT));
            }
        });

        textView3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView4.setText(new String(Base64.decode(textView2.getText().toString(),Base64.DEFAULT)));

            }
        });


    }
}
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".BaseActivity">
   <EditText
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/edt"
       android:paddingTop="30dp"
       />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv1"
        android:text="Encode"
        android:textSize="20dp"
        android:padding="20dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv2"

        android:textSize="20dp"
        android:padding="20dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv3"
        android:text="decode"
        android:textSize="20dp"
        android:padding="20dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv4"
        android:textSize="20dp"
        android:padding="20dp"


        />
</LinearLayout>

Android API용byte[]로.Base64String인코더

byte[] data=new byte[];
String Base64encodeString=android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);

언급URL : https://stackoverflow.com/questions/7360403/does-anyone-know-how-to-decode-and-encode-a-string-in-base64-using-base64

반응형