3

I'm decoding messages with javax.crypto.Cipher and as an output I get byte[]. What is the fastest way to check if my key is correct and byte[] is valid string?

001
  • 13,291
  • 5
  • 35
  • 66
marcelby
  • 83
  • 1
  • 2
  • 5
  • Getting a vaid UTF-8 string doesn't guarantee that the key is valid. What are you trying to achieve? – JB Nizet Oct 20 '17 at 20:12

1 Answers1

7

Try This :-

public boolean checkUTF8(byte[] barr){

        CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
        ByteBuffer buf = ByteBuffer.wrap(barr);

        try {
            decoder.decode(buf);

        }
        catch(CharacterCodingException e){
            return false;
        }

        return true;
    }
Max08
  • 955
  • 1
  • 7
  • 16