Path: blob/master/test/jdk/javax/crypto/Mac/ByteBuffers.java
41149 views
/*1* Copyright (c) 2003, 2007, 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 Mac.update(ByteBuffer) method27* @author Andreas Sterbenz28* @key randomness29*/3031import java.util.*;32import java.nio.*;3334import java.security.*;3536import javax.crypto.*;37import javax.crypto.spec.*;3839public class ByteBuffers {4041public static void main(String[] args) throws Exception {42Provider p = Security.getProvider("SunJCE");43Random random = new Random();44int n = 10 * 1024;45byte[] t = new byte[n];46random.nextBytes(t);4748byte[] keyBytes = new byte[16];49random.nextBytes(keyBytes);50SecretKey key = new SecretKeySpec(keyBytes, "HmacMD5");5152Mac mac = Mac.getInstance("HmacMD5");53mac.init(key);54byte[] macValue = mac.doFinal(t);5556// test 1: ByteBuffer with an accessible backing array57ByteBuffer b1 = ByteBuffer.allocate(n + 256);58b1.position(random.nextInt(256));59b1.limit(b1.position() + n);60ByteBuffer b2 = b1.slice();61b2.put(t);62b2.clear();63verify(mac, macValue, b2, random);6465// test 2: direct ByteBuffer66ByteBuffer b3 = ByteBuffer.allocateDirect(t.length);67b3.put(t);68b3.clear();69verify(mac, macValue, b3, random);7071// test 3: ByteBuffer without an accessible backing array72b2.clear();73ByteBuffer b4 = b2.asReadOnlyBuffer();74verify(mac, macValue, b4, random);7576System.out.println("All tests passed");77}7879private static void verify(Mac mac, byte[] macValue, ByteBuffer b, Random random) throws Exception {80int lim = b.limit();81b.limit(random.nextInt(lim));82mac.update(b);83if (b.hasRemaining()) {84throw new Exception("Buffer not consumed");85}86b.limit(lim);87mac.update(b);88if (b.hasRemaining()) {89throw new Exception("Buffer not consumed");90}91byte[] newMacValue = mac.doFinal();92if (Arrays.equals(macValue, newMacValue) == false) {93throw new Exception("Mac did not verify");94}95}96}979899