Path: blob/master/test/jdk/sun/security/mscapi/RSAEncryptDecrypt.java
41149 views
/*1* Copyright (c) 2006, 2018, 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*/222324/**25* @test26* @bug 6457422 6931562 818057027* @summary Confirm that plaintext can be encrypted and then decrypted using the28* RSA cipher in the SunMSCAPI crypto provider. NOTE: The RSA cipher is29* absent from the SunMSCAPI provider in OpenJDK builds.30* @requires os.family == "windows"31*/3233import javax.crypto.Cipher;34import java.security.GeneralSecurityException;35import java.security.KeyPairGenerator;36import java.security.KeyPair;37import java.security.Key;3839public class RSAEncryptDecrypt {40public static final byte[] PLAINTEXT = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6};4142public static void main(String[] args) throws Exception {4344KeyPairGenerator generator =45KeyPairGenerator.getInstance("RSA", "SunMSCAPI");4647KeyPair keyPair = generator.generateKeyPair();48Key publicKey = keyPair.getPublic();49Key privateKey = keyPair.getPrivate();5051Cipher cipher = null;5253try {54cipher = Cipher.getInstance("RSA", "SunMSCAPI");5556} catch (GeneralSecurityException e) {57System.out.println("Cipher not supported by provider, skipping...");58return;59}6061cipher.init(Cipher.ENCRYPT_MODE, publicKey);62displayBytes("Plaintext data:", PLAINTEXT);63byte[] data = cipher.doFinal(PLAINTEXT);64displayBytes("Encrypted data:", data);6566cipher.init(Cipher.DECRYPT_MODE, privateKey);67data = cipher.doFinal(data);68displayBytes("Decrypted data:", data);69}7071private static void displayBytes(String label, byte[] bytes) {72System.out.println(label + " [length=" + bytes.length + "]");73for (byte b : bytes) {74System.out.print("0x" + Integer.toHexString(b & 0xFF) + " ");75}76System.out.println();77}78}798081