IT이야기

Base 64 인코딩 및 디코딩 예시 코드

cyworld 2022. 6. 6. 10:37
반응형

Base 64 인코딩 및 디코딩 예시 코드

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학급
  • Base64 전송

수신 종료:

  • 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);

이 밖에 코드화된 문자열을 디코딩하는 방법에 대한 정보를 검색하는 동안 여기에 오게 된 다른 사람에게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 라이브러리를 사용하고 있습니다.

Kotlin MB가 이것을 사용하는 것이 좋습니다.

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())

이렇게 사용하는 것보다 Kotlin을 사용하는 경우

인코딩의 경우

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");

위의 많은 답변 중 몇 개는 나에게 효과가 없지만, 그 중 몇 개는 예외 없이 올바른 방법으로 처리됩니다.여기 완벽한 솔루션 작업이 추가되어 있습니다.저도 마찬가지입니다.

//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 [ ]

'198.1989.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);

자세한 내용은 이 링크를 참조하십시오.

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)));

            }
        });


    }
}

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()
    <?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/base-64-encode-and-decode-example-code

반응형