简体   繁体   中英

how to write code in java to convert plaintext into hexadecimal?

String key="this is stack Overflow i am implementing aes algorithm"; //plaintext
String binary=stringToBinary(key); //convertion from plain text to binarydigits
String res[]=split_at(binary,8); //split binary digits into 8 bits
int c=0,r=0;

for(int i=0;i<res.length;i++) //convert each 8 bits into hexadecimal
{
    userKey[r][c]=binaryToHex(res[i]);
    c++;
    if(c==4)
    {
        c=0;
        r++;
        if(r==4)
        break;
    }
}
public static String[][] split_at(String str,int no)//method
{
    int i=0;
    int x=0;
    int l=str.length();
    String res[]=new String[(l/no)+1];
    int f=0;
    while(no<1){
        res[f]=str.substring(i,no);
        i=i+x;
        no=no+x;
        f++;
    }
    if(i<1){
        res[f]=str.substring(i,1);
    }
    return res;
}

I have tried this.but i dont know that it is correct or not.tell me is this correct process or not?if not then suggest me how to convert plaintext into hexa decimal.

Convert each character of the string to an int :

int character = (int) str.charAt(i);

Then get a hex representation of the int :

String hexString = Integer.toHexString(character);

get every character, parse to integer and convert it to hexadecimal

Example:

public static void main(String args[]) throws InterruptedException {
String key = "Hello world";// plaintext
byte[] x = key.getBytes();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < x.length; i++) {
    int b = (int) x[i];
    sb.append(Integer.toHexString(b));
}
System.out.println(sb.toString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM