marcelby
marcelby

Reputation: 93

How to check if byte array is valid UTF-8 String

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?

Upvotes: 4

Views: 4545

Answers (1)

Max08
Max08

Reputation: 1025

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

Upvotes: 8

Related Questions