Java strings storing byte arrays

I want to keep an array of bytes wrapped in a String object. Here is the script

  • The user enters a password.
  • The bytes of this password are obtained using the getBytes () String method.
  • These bytes are encrypted using the java crypo package.
  • These bytes are then converted to String using the new String constructor (bytes [])
  • This string is stored or otherwise transmitted (does not change)
  • The bytes of this string are received, and they differ from the encoded bytes.

Here is a snippet of code describing what I'm talking about.

String s = "test123";
byte[] a = s.getBytes();
byte[] b = env.encrypt(a);
String t = new String(b);
byte[] c = t.getBytes();
byte[] d = env.decrypt(c);

Where env.encrypt () and env.decrypt () do encryption and decryption. The problem I am facing is that array b has length 8 and array c has length 16. I think they will be equal. What's going on here? I tried to change the code as shown below.

String s = "test123";
Charset charset = Charset.getDefaultCharset();
byte[] a = s.getBytes(charset);
byte[] b = env.encrypt(a);
String t = new String(b, charset);
byte[] c = t.getBytes(charset);
byte[] d = env.decrypt(c);

.

?

+3
7

String. - Base64, .

, base64 Java: http://iharder.sourceforge.net/current/java/base64/

+16

, String(byte[]). , Java a String , 16 , 8 , . . , .

:

String s = "test123";
byte[] a = s.getBytes();

, , 8 , - Windows-1252 iso-8859-1 UTF-8.

byte[] b = env.encrypt(a);

b , , , , . , .

String t = new String(b);

Java . , . Java 16- .

byte[] c = t.getBytes();

, b, . , c 16 ; , , , t .

byte[] d = env.decrypt(c);

, c - , , .

:

  • . , , .
  • Base64 :

    byte[] cypherBytes = env.encrypt(getBytes(plainText));
    StringBuffer cypherText = new StringBuffer(cypherBytes.length * 2);
    for (byte b : cypherBytes) {
      String hex = String.format("%02X", b); //$NON-NLS-1$
      cypherText.append(hex);
    }
    return cypherText.toString();
    

:

ASCII, , .

:

String s = "tést123";
byte[] a = s.getBytes();
byte[] b = env.encrypt(a);

String s = "tést123";
byte[] a = s.getBytes("UTF-8");
byte[] b = env.encrypt(a);

- a UTF-8, ( ​​UTF-8). , , A) , B) . , . - , , , , .

: , . , , .

+11

Un-Unicode ( ). , , , . , , ; ISO-8859-1.

, byte[] .

+4

String (byte []) .

. , , .

- Commons Code c hex base64.

, , ?

+3

. ascii ( ). , , . .

. String ( , ).

+2

StringWrapper, String []. "ISO-8859-1", , char 8 16. / .

+1

, , , , . , b env.encrypt, c .getBytes, .

0

Source: https://habr.com/ru/post/1715465/


All Articles