Path: blob/master/test/jdk/java/security/MessageDigest/ByteBuffers.java
41152 views
/*1* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 484484726* @summary Test the MessageDigest.update(ByteBuffer) method27* @author Andreas Sterbenz28* @key randomness29*/3031import java.util.*;32import java.nio.*;3334import java.security.*;3536public class ByteBuffers {3738public static void main(String[] args) throws Exception {39Provider p = Security.getProvider("SUN");40Random random = new Random();41int n = 10 * 1024;42byte[] t = new byte[n];43random.nextBytes(t);4445MessageDigest md = MessageDigest.getInstance("MD5", p);46byte[] d1 = md.digest(t);4748// test 1: ByteBuffer with an accessible backing array49ByteBuffer b1 = ByteBuffer.allocate(n + 256);50b1.position(random.nextInt(256));51b1.limit(b1.position() + n);52ByteBuffer b2 = b1.slice();53b2.put(t);54b2.clear();55byte[] d2 = digest(md, b2, random);56if (Arrays.equals(d1, d2) == false) {57throw new Exception("Test 1 failed");58}5960// test 2: direct ByteBuffer61ByteBuffer b3 = ByteBuffer.allocateDirect(t.length);62b3.put(t);63b3.clear();64byte[] d3 = digest(md, b3, random);65if (Arrays.equals(d1, d3) == false) {66throw new Exception("Test 2 failed");67}6869// test 3: ByteBuffer without an accessible backing array70b2.clear();71ByteBuffer b4 = b2.asReadOnlyBuffer();72byte[] d4 = digest(md, b4, random);73if (Arrays.equals(d1, d4) == false) {74throw new Exception("Test 3 failed");75}76System.out.println("All tests passed");77}7879private static byte[] digest(MessageDigest md, ByteBuffer b, Random random) throws Exception {80int lim = b.limit();81b.limit(random.nextInt(lim));82md.update(b);83if (b.hasRemaining()) {84throw new Exception("Buffer not consumed");85}86b.limit(lim);87md.update(b);88if (b.hasRemaining()) {89throw new Exception("Buffer not consumed");90}91return md.digest();92}93}949596