Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/sun/security/pkcs11/SecureRandom/TestDeserialization.java
38855 views
/*1* Copyright (c) 2010, 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 683784726* @summary Ensure a deserialized PKCS#11 SecureRandom is functional.27* @library ..28*/2930import java.security.*;31import java.io.*;3233public class TestDeserialization extends PKCS11Test {3435public void main(Provider p) throws Exception {36// Skip this test for providers not found by java.security.Security37if (Security.getProvider(p.getName()) != p) {38System.out.println("Skip test for provider " + p.getName());39return;40}41SecureRandom r;42try {43r = SecureRandom.getInstance("PKCS11", p);44System.out.println("SecureRandom instance " + r);45} catch (NoSuchAlgorithmException e) {46System.out.println("Provider " + p +47" does not support SecureRandom, skipping");48e.printStackTrace();49return;50}51r.setSeed(System.currentTimeMillis());52byte[] buf = new byte[16];53byte[] ser = toByteArray(r);54System.out.println("Serialized Len = " + ser.length);55SecureRandom r2 = fromByteArray(ser);56System.out.println("Deserialized into " + r2);57r2.nextBytes(buf);58System.out.println("Done");59}6061public static void main(String[] args) throws Exception {62main(new TestDeserialization());63}6465private byte[] toByteArray(SecureRandom r) throws Exception {66ByteArrayOutputStream out = new ByteArrayOutputStream(1024);67ObjectOutputStream outStream = null;68try {69outStream = new ObjectOutputStream(out);70outStream.writeObject(r);71return out.toByteArray();72} finally {73if (outStream != null) {74outStream.close();75}76}77}7879private SecureRandom fromByteArray(byte[] buf) throws Exception {80SecureRandom r = null;81ByteArrayInputStream is = new ByteArrayInputStream(buf);82ObjectInputStream ois = null;83try {84ois = new ObjectInputStream(is);85r = (SecureRandom) ois.readObject();86} finally {87if (ois != null) {88ois.close();89}90}91return r;92}93}949596