8080462: Update SunPKCS11 provider with PKCS11 v2.40 support

Added support for GCM, PSS, and other mechanisms

Reviewed-by: jnimeh
This commit is contained in:
Valerie Peng 2019-06-11 21:30:28 +00:00
parent 9115f920d2
commit 8813b93095
38 changed files with 6567 additions and 2825 deletions

View File

@ -0,0 +1,153 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.util;
import java.io.IOException;
import java.security.AlgorithmParametersSpi;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import javax.crypto.spec.GCMParameterSpec;
import sun.security.util.HexDumpEncoder;
import sun.security.util.*;
/**
* This class implements the parameter set used with
* GCM encryption, which is defined in RFC 5084 as follows:
*
* <pre>
* GCMParameters ::= SEQUENCE {
* aes-iv OCTET STRING, -- recommended size is 12 octets
* aes-tLen AES-GCM-ICVlen DEFAULT 12 }
*
* AES-GCM-ICVlen ::= INTEGER (12 | 13 | 14 | 15 | 16)
*
* </pre>
*
* @since 13
*/
public final class GCMParameters extends AlgorithmParametersSpi {
// the iv
private byte[] iv;
// the tag length in bytes
private int tLen;
public GCMParameters() {}
protected void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException {
if (!(paramSpec instanceof GCMParameterSpec)) {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
GCMParameterSpec gps = (GCMParameterSpec) paramSpec;
// need to convert from bits to bytes for ASN.1 encoding
this.tLen = gps.getTLen()/8;
if (this.tLen < 12 || this.tLen > 16 ) {
throw new InvalidParameterSpecException
("GCM parameter parsing error: unsupported tag len: " +
this.tLen);
}
this.iv = gps.getIV();
}
protected void engineInit(byte[] encoded) throws IOException {
DerValue val = new DerValue(encoded);
// check if IV or params
if (val.tag == DerValue.tag_Sequence) {
byte[] iv = val.data.getOctetString();
int tLen;
if (val.data.available() != 0) {
tLen = val.data.getInteger();
if (tLen < 12 || tLen > 16 ) {
throw new IOException
("GCM parameter parsing error: unsupported tag len: " +
tLen);
}
if (val.data.available() != 0) {
throw new IOException
("GCM parameter parsing error: extra data");
}
} else {
tLen = 12;
}
this.iv = iv.clone();
this.tLen = tLen;
} else {
throw new IOException("GCM parameter parsing error: no SEQ tag");
}
}
protected void engineInit(byte[] encoded, String decodingMethod)
throws IOException {
engineInit(encoded);
}
protected <T extends AlgorithmParameterSpec>
T engineGetParameterSpec(Class<T> paramSpec)
throws InvalidParameterSpecException {
if (GCMParameterSpec.class.isAssignableFrom(paramSpec)) {
return paramSpec.cast(new GCMParameterSpec(tLen * 8, iv));
} else {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
}
protected byte[] engineGetEncoded() throws IOException {
DerOutputStream out = new DerOutputStream();
DerOutputStream bytes = new DerOutputStream();
bytes.putOctetString(iv);
// Only put non-default values
if (tLen != 12) {
bytes.putInteger(tLen);
}
out.write(DerValue.tag_Sequence, bytes);
return out.toByteArray();
}
protected byte[] engineGetEncoded(String encodingMethod)
throws IOException {
return engineGetEncoded();
}
/*
* Returns a formatted string describing the parameters.
*/
protected String engineToString() {
String LINE_SEP = System.lineSeparator();
HexDumpEncoder encoder = new HexDumpEncoder();
StringBuilder sb
= new StringBuilder(LINE_SEP + " iv:" + LINE_SEP + "["
+ encoder.encodeBuffer(iv) + "]");
sb.append(LINE_SEP + "tLen(bits):" + LINE_SEP + tLen*8 + LINE_SEP);
return sb.toString();
}
}

View File

@ -0,0 +1,750 @@
/* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.pkcs11;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Locale;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import sun.nio.ch.DirectBuffer;
import sun.security.jca.JCAUtil;
import sun.security.pkcs11.wrapper.*;
import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
/**
* P11 AEAD Cipher implementation class. This class currently supports
* AES with GCM mode.
*
* Note that AEAD modes do not use padding, so this class does not have
* its own padding impl. In addition, NSS CKM_AES_GCM only supports single-part
* encryption/decryption, thus the current impl uses PKCS#11 C_Encrypt/C_Decrypt
* calls and buffers data until doFinal is called.
*
* Note that PKCS#11 standard currently only supports GCM and CCM AEAD modes.
* There are no provisions for other AEAD modes yet.
*
* @since 13
*/
final class P11AEADCipher extends CipherSpi {
// mode constant for GCM mode
private static final int MODE_GCM = 10;
// default constants for GCM
private static final int GCM_DEFAULT_TAG_LEN = 16;
private static final int GCM_DEFAULT_IV_LEN = 16;
private static final String ALGO = "AES";
// token instance
private final Token token;
// mechanism id
private final long mechanism;
// mode, one of MODE_* above
private final int blockMode;
// acceptable key size, -1 if more than 1 key sizes are accepted
private final int fixedKeySize;
// associated session, if any
private Session session = null;
// key, if init() was called
private P11Key p11Key = null;
// flag indicating whether an operation is initialized
private boolean initialized = false;
// falg indicating encrypt or decrypt mode
private boolean encrypt = true;
// parameters
private byte[] iv = null;
private int tagLen = -1;
private SecureRandom random = JCAUtil.getSecureRandom();
// dataBuffer is cleared upon doFinal calls
private ByteArrayOutputStream dataBuffer = new ByteArrayOutputStream();
// aadBuffer is cleared upon successful init calls
private ByteArrayOutputStream aadBuffer = new ByteArrayOutputStream();
private boolean updateCalled = false;
private boolean requireReinit = false;
private P11Key lastEncKey = null;
private byte[] lastEncIv = null;
P11AEADCipher(Token token, String algorithm, long mechanism)
throws PKCS11Exception, NoSuchAlgorithmException {
super();
this.token = token;
this.mechanism = mechanism;
String[] algoParts = algorithm.split("/");
if (algoParts.length != 3) {
throw new ProviderException("Unsupported Transformation format: " +
algorithm);
}
if (!algoParts[0].startsWith("AES")) {
throw new ProviderException("Only support AES for AEAD cipher mode");
}
int index = algoParts[0].indexOf('_');
if (index != -1) {
// should be well-formed since we specify what we support
fixedKeySize = Integer.parseInt(algoParts[0].substring(index+1)) >> 3;
} else {
fixedKeySize = -1;
}
this.blockMode = parseMode(algoParts[1]);
if (!algoParts[2].equals("NoPadding")) {
throw new ProviderException("Only NoPadding is supported for AEAD cipher mode");
}
}
protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
// Disallow change of mode for now since currently it's explicitly
// defined in transformation strings
throw new NoSuchAlgorithmException("Unsupported mode " + mode);
}
private int parseMode(String mode) throws NoSuchAlgorithmException {
mode = mode.toUpperCase(Locale.ENGLISH);
int result;
if (mode.equals("GCM")) {
result = MODE_GCM;
} else {
throw new NoSuchAlgorithmException("Unsupported mode " + mode);
}
return result;
}
// see JCE spec
protected void engineSetPadding(String padding)
throws NoSuchPaddingException {
// Disallow change of padding for now since currently it's explicitly
// defined in transformation strings
throw new NoSuchPaddingException("Unsupported padding " + padding);
}
// see JCE spec
protected int engineGetBlockSize() {
return 16; // constant; only AES is supported
}
// see JCE spec
protected int engineGetOutputSize(int inputLen) {
return doFinalLength(inputLen);
}
// see JCE spec
protected byte[] engineGetIV() {
return (iv == null) ? null : iv.clone();
}
// see JCE spec
protected AlgorithmParameters engineGetParameters() {
if (encrypt && iv == null && tagLen == -1) {
switch (blockMode) {
case MODE_GCM:
iv = new byte[GCM_DEFAULT_IV_LEN];
tagLen = GCM_DEFAULT_TAG_LEN;
break;
default:
throw new ProviderException("Unsupported mode");
}
random.nextBytes(iv);
}
try {
AlgorithmParameterSpec spec;
String apAlgo;
switch (blockMode) {
case MODE_GCM:
apAlgo = "GCM";
spec = new GCMParameterSpec(tagLen << 3, iv);
break;
default:
throw new ProviderException("Unsupported mode");
}
AlgorithmParameters params =
AlgorithmParameters.getInstance(apAlgo);
params.init(spec);
return params;
} catch (GeneralSecurityException e) {
// NoSuchAlgorithmException, NoSuchProviderException
// InvalidParameterSpecException
throw new ProviderException("Could not encode parameters", e);
}
}
// see JCE spec
protected void engineInit(int opmode, Key key, SecureRandom sr)
throws InvalidKeyException {
if (opmode == Cipher.DECRYPT_MODE) {
throw new InvalidKeyException("Parameters required for decryption");
}
updateCalled = false;
try {
implInit(opmode, key, null, -1, sr);
} catch (InvalidAlgorithmParameterException e) {
throw new InvalidKeyException("init() failed", e);
}
}
// see JCE spec
protected void engineInit(int opmode, Key key,
AlgorithmParameterSpec params, SecureRandom sr)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (opmode == Cipher.DECRYPT_MODE && params == null) {
throw new InvalidAlgorithmParameterException
("Parameters required for decryption");
}
updateCalled = false;
byte[] ivValue = null;
int tagLen = -1;
if (params != null) {
switch (blockMode) {
case MODE_GCM:
if (!(params instanceof GCMParameterSpec)) {
throw new InvalidAlgorithmParameterException
("Only GCMParameterSpec is supported");
}
ivValue = ((GCMParameterSpec) params).getIV();
tagLen = ((GCMParameterSpec) params).getTLen() >> 3;
break;
default:
throw new ProviderException("Unsupported mode");
}
}
implInit(opmode, key, ivValue, tagLen, sr);
}
// see JCE spec
protected void engineInit(int opmode, Key key, AlgorithmParameters params,
SecureRandom sr)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (opmode == Cipher.DECRYPT_MODE && params == null) {
throw new InvalidAlgorithmParameterException
("Parameters required for decryption");
}
updateCalled = false;
try {
AlgorithmParameterSpec paramSpec = null;
if (params != null) {
switch (blockMode) {
case MODE_GCM:
paramSpec =
params.getParameterSpec(GCMParameterSpec.class);
break;
default:
throw new ProviderException("Unsupported mode");
}
}
engineInit(opmode, key, paramSpec, sr);
} catch (InvalidParameterSpecException ex) {
throw new InvalidAlgorithmParameterException(ex);
}
}
// actual init() implementation
private void implInit(int opmode, Key key, byte[] iv, int tagLen,
SecureRandom sr)
throws InvalidKeyException, InvalidAlgorithmParameterException {
reset(true);
if (fixedKeySize != -1 && key.getEncoded().length != fixedKeySize) {
throw new InvalidKeyException("Key size is invalid");
}
P11Key newKey = P11SecretKeyFactory.convertKey(token, key, ALGO);
switch (opmode) {
case Cipher.ENCRYPT_MODE:
encrypt = true;
requireReinit = Arrays.equals(iv, lastEncIv) &&
(newKey == lastEncKey);
if (requireReinit) {
throw new InvalidAlgorithmParameterException
("Cannot reuse iv for GCM encryption");
}
break;
case Cipher.DECRYPT_MODE:
encrypt = false;
requireReinit = false;
break;
default:
throw new InvalidAlgorithmParameterException
("Unsupported mode: " + opmode);
}
// decryption without parameters is checked in all engineInit() calls
if (sr != null) {
this.random = sr;
}
if (iv == null && tagLen == -1) {
// generate default values
switch (blockMode) {
case MODE_GCM:
iv = new byte[GCM_DEFAULT_IV_LEN];
this.random.nextBytes(iv);
tagLen = GCM_DEFAULT_TAG_LEN;
break;
default:
throw new ProviderException("Unsupported mode");
}
}
this.iv = iv;
this.tagLen = tagLen;
this.p11Key = newKey;
try {
initialize();
} catch (PKCS11Exception e) {
throw new InvalidKeyException("Could not initialize cipher", e);
}
}
private void cancelOperation() {
try {
if (session.hasObjects() == false) {
session = token.killSession(session);
return;
} else {
// cancel operation by finishing it
int bufLen = doFinalLength(0);
byte[] buffer = new byte[bufLen];
if (encrypt) {
token.p11.C_Encrypt(session.id(), 0, buffer, 0, bufLen,
0, buffer, 0, bufLen);
} else {
token.p11.C_Decrypt(session.id(), 0, buffer, 0, bufLen,
0, buffer, 0, bufLen);
}
}
} catch (PKCS11Exception e) {
throw new ProviderException("Cancel failed", e);
}
}
private void ensureInitialized() throws PKCS11Exception {
if (initialized && aadBuffer.size() > 0) {
// need to cancel first to avoid CKR_OPERATION_ACTIVE
reset(true);
}
if (!initialized) {
initialize();
}
}
private void initialize() throws PKCS11Exception {
if (p11Key == null) {
throw new ProviderException(
"Operation cannot be performed without"
+ " calling engineInit first");
}
if (requireReinit) {
throw new IllegalStateException
("Must use either different key or iv for GCM encryption");
}
token.ensureValid();
byte[] aad = (aadBuffer.size() > 0? aadBuffer.toByteArray() : null);
long p11KeyID = p11Key.getKeyID();
try {
if (session == null) {
session = token.getOpSession();
}
CK_MECHANISM mechWithParams;
switch (blockMode) {
case MODE_GCM:
mechWithParams = new CK_MECHANISM(mechanism,
new CK_GCM_PARAMS(tagLen << 3, iv, aad));
break;
default:
throw new ProviderException("Unsupported mode: " + blockMode);
}
if (encrypt) {
token.p11.C_EncryptInit(session.id(), mechWithParams,
p11KeyID);
} else {
token.p11.C_DecryptInit(session.id(), mechWithParams,
p11KeyID);
}
} catch (PKCS11Exception e) {
//e.printStackTrace();
p11Key.releaseKeyID();
session = token.releaseSession(session);
throw e;
} finally {
dataBuffer.reset();
aadBuffer.reset();
}
initialized = true;
}
// if doFinal(inLen) is called, how big does the output buffer have to be?
private int doFinalLength(int inLen) {
if (inLen < 0) {
throw new ProviderException("Invalid negative input length");
}
int result = inLen + dataBuffer.size();
if (encrypt) {
result += tagLen;
} else {
// PKCS11Exception: CKR_BUFFER_TOO_SMALL
//result -= tagLen;
}
return result;
}
// reset the states to the pre-initialized values
private void reset(boolean doCancel) {
if (!initialized) {
return;
}
try {
if (session == null) {
return;
}
if (doCancel && token.explicitCancel) {
cancelOperation();
}
} finally {
p11Key.releaseKeyID();
session = token.releaseSession(session);
}
initialized = false;
}
// see JCE spec
protected byte[] engineUpdate(byte[] in, int inOfs, int inLen) {
updateCalled = true;
int n = implUpdate(in, inOfs, inLen);
return new byte[0];
}
// see JCE spec
protected int engineUpdate(byte[] in, int inOfs, int inLen, byte[] out,
int outOfs) throws ShortBufferException {
updateCalled = true;
implUpdate(in, inOfs, inLen);
return 0;
}
// see JCE spec
@Override
protected int engineUpdate(ByteBuffer inBuffer, ByteBuffer outBuffer)
throws ShortBufferException {
updateCalled = true;
implUpdate(inBuffer);
return 0;
}
// see JCE spec
@Override
protected synchronized void engineUpdateAAD(byte[] src, int srcOfs, int srcLen)
throws IllegalStateException {
if ((src == null) || (srcOfs < 0) || (srcOfs + srcLen > src.length)) {
throw new IllegalArgumentException("Invalid AAD");
}
if (requireReinit) {
throw new IllegalStateException
("Must use either different key or iv for GCM encryption");
}
if (p11Key == null) {
throw new IllegalStateException("Need to initialize Cipher first");
}
if (updateCalled) {
throw new IllegalStateException
("Update has been called; no more AAD data");
}
aadBuffer.write(src, srcOfs, srcLen);
}
// see JCE spec
@Override
protected void engineUpdateAAD(ByteBuffer src)
throws IllegalStateException {
if (src == null) {
throw new IllegalArgumentException("Invalid AAD");
}
byte[] srcBytes = new byte[src.remaining()];
src.get(srcBytes);
engineUpdateAAD(srcBytes, 0, srcBytes.length);
}
// see JCE spec
protected byte[] engineDoFinal(byte[] in, int inOfs, int inLen)
throws IllegalBlockSizeException, BadPaddingException {
int minOutLen = doFinalLength(inLen);
try {
byte[] out = new byte[minOutLen];
int n = engineDoFinal(in, inOfs, inLen, out, 0);
return P11Util.convert(out, 0, n);
} catch (ShortBufferException e) {
// convert since the output length is calculated by doFinalLength()
throw new ProviderException(e);
} finally {
updateCalled = false;
}
}
// see JCE spec
protected int engineDoFinal(byte[] in, int inOfs, int inLen, byte[] out,
int outOfs) throws ShortBufferException, IllegalBlockSizeException,
BadPaddingException {
try {
return implDoFinal(in, inOfs, inLen, out, outOfs, out.length - outOfs);
} finally {
updateCalled = false;
}
}
// see JCE spec
@Override
protected int engineDoFinal(ByteBuffer inBuffer, ByteBuffer outBuffer)
throws ShortBufferException, IllegalBlockSizeException,
BadPaddingException {
try {
return implDoFinal(inBuffer, outBuffer);
} finally {
updateCalled = false;
}
}
private int implUpdate(byte[] in, int inOfs, int inLen) {
if (inLen > 0) {
updateCalled = true;
try {
ensureInitialized();
} catch (PKCS11Exception e) {
//e.printStackTrace();
reset(false);
throw new ProviderException("update() failed", e);
}
dataBuffer.write(in, inOfs, inLen);
}
// always 0 as NSS only supports single-part encryption/decryption
return 0;
}
private int implUpdate(ByteBuffer inBuf) {
int inLen = inBuf.remaining();
if (inLen > 0) {
try {
ensureInitialized();
} catch (PKCS11Exception e) {
reset(false);
throw new ProviderException("update() failed", e);
}
byte[] data = new byte[inLen];
inBuf.get(data);
dataBuffer.write(data, 0, data.length);
}
// always 0 as NSS only supports single-part encryption/decryption
return 0;
}
private int implDoFinal(byte[] in, int inOfs, int inLen,
byte[] out, int outOfs, int outLen)
throws ShortBufferException, IllegalBlockSizeException,
BadPaddingException {
int requiredOutLen = doFinalLength(inLen);
if (outLen < requiredOutLen) {
throw new ShortBufferException();
}
boolean doCancel = true;
try {
ensureInitialized();
if (dataBuffer.size() > 0) {
if (in != null && inOfs > 0 && inLen > 0 &&
inOfs < (in.length - inLen)) {
dataBuffer.write(in, inOfs, inLen);
}
in = dataBuffer.toByteArray();
inOfs = 0;
inLen = in.length;
}
int k = 0;
if (encrypt) {
k = token.p11.C_Encrypt(session.id(), 0, in, inOfs, inLen,
0, out, outOfs, outLen);
doCancel = false;
} else {
// Special handling to match SunJCE provider behavior
if (inLen == 0) {
return 0;
}
k = token.p11.C_Decrypt(session.id(), 0, in, inOfs, inLen,
0, out, outOfs, outLen);
doCancel = false;
}
return k;
} catch (PKCS11Exception e) {
doCancel = false;
handleException(e);
throw new ProviderException("doFinal() failed", e);
} finally {
if (encrypt) {
lastEncKey = this.p11Key;
lastEncIv = this.iv;
requireReinit = true;
}
reset(doCancel);
}
}
private int implDoFinal(ByteBuffer inBuffer, ByteBuffer outBuffer)
throws ShortBufferException, IllegalBlockSizeException,
BadPaddingException {
int outLen = outBuffer.remaining();
int inLen = inBuffer.remaining();
int requiredOutLen = doFinalLength(inLen);
if (outLen < requiredOutLen) {
throw new ShortBufferException();
}
boolean doCancel = true;
try {
ensureInitialized();
long inAddr = 0;
byte[] in = null;
int inOfs = 0;
if (dataBuffer.size() > 0) {
if (inLen > 0) {
byte[] temp = new byte[inLen];
inBuffer.get(temp);
dataBuffer.write(temp, 0, temp.length);
}
in = dataBuffer.toByteArray();
inOfs = 0;
inLen = in.length;
} else {
if (inBuffer instanceof DirectBuffer) {
inAddr = ((DirectBuffer) inBuffer).address();
inOfs = inBuffer.position();
} else {
if (inBuffer.hasArray()) {
in = inBuffer.array();
inOfs = inBuffer.position() + inBuffer.arrayOffset();
} else {
in = new byte[inLen];
inBuffer.get(in);
}
}
}
long outAddr = 0;
byte[] outArray = null;
int outOfs = 0;
if (outBuffer instanceof DirectBuffer) {
outAddr = ((DirectBuffer) outBuffer).address();
outOfs = outBuffer.position();
} else {
if (outBuffer.hasArray()) {
outArray = outBuffer.array();
outOfs = outBuffer.position() + outBuffer.arrayOffset();
} else {
outArray = new byte[outLen];
}
}
int k = 0;
if (encrypt) {
k = token.p11.C_Encrypt(session.id(), inAddr, in, inOfs, inLen,
outAddr, outArray, outOfs, outLen);
doCancel = false;
} else {
// Special handling to match SunJCE provider behavior
if (inLen == 0) {
return 0;
}
k = token.p11.C_Decrypt(session.id(), inAddr, in, inOfs, inLen,
outAddr, outArray, outOfs, outLen);
doCancel = false;
}
outBuffer.position(outBuffer.position() + k);
return k;
} catch (PKCS11Exception e) {
doCancel = false;
handleException(e);
throw new ProviderException("doFinal() failed", e);
} finally {
if (encrypt) {
lastEncKey = this.p11Key;
lastEncIv = this.iv;
requireReinit = true;
}
reset(doCancel);
}
}
private void handleException(PKCS11Exception e)
throws ShortBufferException, IllegalBlockSizeException,
BadPaddingException {
long errorCode = e.getErrorCode();
if (errorCode == CKR_BUFFER_TOO_SMALL) {
throw (ShortBufferException)
(new ShortBufferException().initCause(e));
} else if (errorCode == CKR_DATA_LEN_RANGE ||
errorCode == CKR_ENCRYPTED_DATA_LEN_RANGE) {
throw (IllegalBlockSizeException)
(new IllegalBlockSizeException(e.toString()).initCause(e));
} else if (errorCode == CKR_ENCRYPTED_DATA_INVALID) {
throw (BadPaddingException)
(new BadPaddingException(e.toString()).initCause(e));
}
}
// see JCE spec
protected byte[] engineWrap(Key key) throws IllegalBlockSizeException,
InvalidKeyException {
// XXX key wrapping
throw new UnsupportedOperationException("engineWrap()");
}
// see JCE spec
protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm,
int wrappedKeyType)
throws InvalidKeyException, NoSuchAlgorithmException {
// XXX key unwrapping
throw new UnsupportedOperationException("engineUnwrap()");
}
// see JCE spec
@Override
protected int engineGetKeySize(Key key) throws InvalidKeyException {
int n = P11SecretKeyFactory.convertKey
(token, key, ALGO).length();
return n;
}
}

View File

@ -0,0 +1,701 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.pkcs11;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import sun.nio.ch.DirectBuffer;
import java.util.Hashtable;
import java.util.Arrays;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
import java.security.interfaces.*;
import sun.security.pkcs11.wrapper.*;
import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
/**
* RSASSA-PSS Signature implementation class. This class currently supports the
* following algorithms:
*
* . RSA-PSS:
* . RSASSA-PSS
* . SHA1withRSASSA-PSS
* . SHA224withRSASSA-PSS
* . SHA256withRSASSA-PSS
* . SHA384withRSASSA-PSS
* . SHA512withRSASSA-PSS
*
* Note that the underlying PKCS#11 token may support complete signature
* algorithm (e.g. CKM_<md>_RSA_PKCS_PSS), or it may just
* implement the signature algorithm without hashing (i.e. CKM_RSA_PKCS_PSS).
* This class uses what is available and adds whatever extra processing
* is needed.
*
* @since 13
*/
final class P11PSSSignature extends SignatureSpi {
private final static boolean DEBUG = false;
// mappings of digest algorithms and their output length in bytes
private static final Hashtable<String, Integer> DIGEST_LENGTHS =
new Hashtable<String, Integer>();
static {
DIGEST_LENGTHS.put("SHA-1", 20);
DIGEST_LENGTHS.put("SHA", 20);
DIGEST_LENGTHS.put("SHA1", 20);
DIGEST_LENGTHS.put("SHA-224", 28);
DIGEST_LENGTHS.put("SHA224", 28);
DIGEST_LENGTHS.put("SHA-256", 32);
DIGEST_LENGTHS.put("SHA256", 32);
DIGEST_LENGTHS.put("SHA-384", 48);
DIGEST_LENGTHS.put("SHA384", 48);
DIGEST_LENGTHS.put("SHA-512", 64);
DIGEST_LENGTHS.put("SHA512", 64);
DIGEST_LENGTHS.put("SHA-512/224", 28);
DIGEST_LENGTHS.put("SHA512/224", 28);
DIGEST_LENGTHS.put("SHA-512/256", 32);
DIGEST_LENGTHS.put("SHA512/256", 32);
}
// utility method for comparing digest algorithms
// NOTE that first argument is assumed to be standard digest name
private static boolean isDigestEqual(String stdAlg, String givenAlg) {
if (stdAlg == null || givenAlg == null) return false;
if (givenAlg.indexOf("-") != -1) {
return stdAlg.equalsIgnoreCase(givenAlg);
} else {
if (stdAlg.equals("SHA-1")) {
return (givenAlg.equalsIgnoreCase("SHA")
|| givenAlg.equalsIgnoreCase("SHA1"));
} else {
StringBuilder sb = new StringBuilder(givenAlg);
// case-insensitive check
if (givenAlg.regionMatches(true, 0, "SHA", 0, 3)) {
givenAlg = sb.insert(3, "-").toString();
return stdAlg.equalsIgnoreCase(givenAlg);
} else {
throw new ProviderException("Unsupported digest algorithm "
+ givenAlg);
}
}
}
}
// token instance
private final Token token;
// algorithm name
private final String algorithm;
// name of the key algorithm, currently just RSA
private static final String KEY_ALGO = "RSA";
// mechanism id
private final CK_MECHANISM mechanism;
// type, one of T_* below
private final int type;
// key instance used, if init*() was called
private P11Key p11Key = null;
// PSS parameters and the flag controlling its access
private PSSParameterSpec sigParams = null;
private boolean isActive = false;
// message digest alg, if implied by the algorithm name
private final String mdAlg;
// message digest, if we do the digesting ourselves
private MessageDigest md = null;
// associated session, if any
private Session session;
// mode, one of M_* below
private int mode;
// flag indicating whether an operation is initialized
private boolean initialized = false;
// buffer, for update(byte)
private final byte[] buffer = new byte[1];
// total number of bytes processed in current operation
private int bytesProcessed = 0;
// constant for signing mode
private final static int M_SIGN = 1;
// constant for verification mode
private final static int M_VERIFY = 2;
// constant for type digesting, we do the hashing ourselves
private final static int T_DIGEST = 1;
// constant for type update, token does everything
private final static int T_UPDATE = 2;
P11PSSSignature(Token token, String algorithm, long mechId)
throws NoSuchAlgorithmException, PKCS11Exception {
super();
this.token = token;
this.algorithm = algorithm;
this.mechanism = new CK_MECHANISM(mechId);
int idx = algorithm.indexOf("with");
this.mdAlg = (idx == -1? null : algorithm.substring(0, idx));
switch ((int)mechId) {
case (int)CKM_SHA1_RSA_PKCS_PSS:
case (int)CKM_SHA224_RSA_PKCS_PSS:
case (int)CKM_SHA256_RSA_PKCS_PSS:
case (int)CKM_SHA384_RSA_PKCS_PSS:
case (int)CKM_SHA512_RSA_PKCS_PSS:
type = T_UPDATE;
break;
case (int)CKM_RSA_PKCS_PSS:
type = T_DIGEST;
break;
default:
throw new ProviderException("Unsupported mechanism: " + mechId);
}
this.md = null;
}
private void ensureInitialized() throws SignatureException {
token.ensureValid();
if (this.p11Key == null) {
throw new SignatureException("Missing key");
}
if (this.sigParams == null) {
if (this.mdAlg == null) {
// PSS Parameters are required for signature verification
throw new SignatureException
("Parameters required for RSASSA-PSS signature");
} else {
int saltLen = DIGEST_LENGTHS.get(this.mdAlg).intValue();
// generate default params for both sign and verify?
this.sigParams = new PSSParameterSpec(this.mdAlg,
"MGF1", new MGF1ParameterSpec(this.mdAlg),
saltLen, PSSParameterSpec.TRAILER_FIELD_BC);
this.mechanism.setParameter(new CK_RSA_PKCS_PSS_PARAMS(
this.mdAlg, "MGF1", this.mdAlg,
DIGEST_LENGTHS.get(this.mdAlg).intValue()));
}
}
if (initialized == false) {
initialize();
}
}
// reset the states to the pre-initialized values
private void reset(boolean doCancel) {
if (!initialized) {
return;
}
initialized = false;
try {
if (session == null) {
return;
}
if (doCancel && token.explicitCancel) {
cancelOperation();
}
} finally {
p11Key.releaseKeyID();
mechanism.freeHandle();
session = token.releaseSession(session);
isActive = false;
}
}
private void cancelOperation() {
token.ensureValid();
if (DEBUG) System.out.print("Cancelling operation");
if (session.hasObjects() == false) {
if (DEBUG) System.out.println(" by killing session");
session = token.killSession(session);
return;
}
// "cancel" operation by finishing it
if (mode == M_SIGN) {
try {
if (type == T_UPDATE) {
if (DEBUG) System.out.println(" by C_SignFinal");
token.p11.C_SignFinal(session.id(), 0);
} else {
byte[] digest =
(md == null? new byte[0] : md.digest());
if (DEBUG) System.out.println(" by C_Sign");
token.p11.C_Sign(session.id(), digest);
}
} catch (PKCS11Exception e) {
throw new ProviderException("cancel failed", e);
}
} else { // M_VERIFY
try {
byte[] signature =
new byte[(p11Key.length() + 7) >> 3];
if (type == T_UPDATE) {
if (DEBUG) System.out.println(" by C_VerifyFinal");
token.p11.C_VerifyFinal(session.id(), signature);
} else {
byte[] digest =
(md == null? new byte[0] : md.digest());
if (DEBUG) System.out.println(" by C_Verify");
token.p11.C_Verify(session.id(), digest, signature);
}
} catch (PKCS11Exception e) {
// will fail since the signature is incorrect
// XXX check error code
}
}
}
// assumes current state is initialized == false
private void initialize() {
if (DEBUG) System.out.println("Initializing");
if (p11Key == null) {
throw new ProviderException(
"No Key found, call initSign/initVerify first");
}
long keyID = p11Key.getKeyID();
try {
if (session == null) {
session = token.getOpSession();
}
if (mode == M_SIGN) {
token.p11.C_SignInit(session.id(), mechanism, keyID);
} else {
token.p11.C_VerifyInit(session.id(), mechanism, keyID);
}
} catch (PKCS11Exception e) {
p11Key.releaseKeyID();
session = token.releaseSession(session);
throw new ProviderException("Initialization failed", e);
}
if (bytesProcessed != 0) {
bytesProcessed = 0;
if (md != null) {
md.reset();
}
}
initialized = true;
isActive = false;
if (DEBUG) System.out.println("Initialized");
}
private void checkKeySize(Key key) throws InvalidKeyException {
if (DEBUG) System.out.print("Checking Key");
if (!key.getAlgorithm().equals(KEY_ALGO)) {
throw new InvalidKeyException("Only " + KEY_ALGO +
" keys are supported");
}
CK_MECHANISM_INFO mechInfo = null;
try {
mechInfo = token.getMechanismInfo(mechanism.mechanism);
} catch (PKCS11Exception e) {
// should not happen, ignore for now
if (DEBUG) {
System.out.println("Unexpected exception");
e.printStackTrace();
}
}
int keySize = 0; // in bytes
if (mechInfo != null) {
// check against available native info
int minKeySize = (int) mechInfo.ulMinKeySize;
int maxKeySize = (int) mechInfo.ulMaxKeySize;
if (key instanceof P11Key) {
keySize = (((P11Key) key).length() + 7) >> 3;
} else if (key instanceof RSAKey) {
keySize = ((RSAKey) key).getModulus().bitLength() >> 3;
} else {
throw new InvalidKeyException("Unrecognized key type " + key);
}
if ((minKeySize != -1) && (keySize < minKeySize)) {
throw new InvalidKeyException(KEY_ALGO +
" key must be at least " + minKeySize + " bytes");
}
if ((maxKeySize != -1) && (keySize > maxKeySize)) {
throw new InvalidKeyException(KEY_ALGO +
" key must be at most " + maxKeySize + " bytes");
}
}
if (this.sigParams != null) {
String digestAlg = this.sigParams.getDigestAlgorithm();
int sLen = this.sigParams.getSaltLength();
int hLen = DIGEST_LENGTHS.get(digestAlg).intValue();
int minKeyLen = Math.addExact(Math.addExact(sLen, hLen), 2);
if (keySize < minKeyLen) {
throw new InvalidKeyException
("Key is too short for current params, need min " + minKeyLen);
}
}
}
private void setSigParams(AlgorithmParameterSpec p)
throws InvalidAlgorithmParameterException {
if (p == null) {
throw new InvalidAlgorithmParameterException("PSS Parameter required");
}
if (!(p instanceof PSSParameterSpec)) {
throw new InvalidAlgorithmParameterException
("Only PSSParameterSpec is supported");
}
// no need to validate again if same as current signature parameters
PSSParameterSpec params = (PSSParameterSpec) p;
if (params == this.sigParams) return;
String digestAlgorithm = params.getDigestAlgorithm();
if (this.mdAlg != null && !isDigestEqual(digestAlgorithm, this.mdAlg)) {
throw new InvalidAlgorithmParameterException
("Digest algorithm in Signature parameters must be " +
this.mdAlg);
}
Integer digestLen = DIGEST_LENGTHS.get(digestAlgorithm);
if (digestLen == null) {
throw new InvalidAlgorithmParameterException
("Unsupported digest algorithm in Signature parameters: " +
digestAlgorithm);
}
if (!(params.getMGFAlgorithm().equalsIgnoreCase("MGF1"))) {
throw new InvalidAlgorithmParameterException("Only supports MGF1");
}
if (params.getTrailerField() != PSSParameterSpec.TRAILER_FIELD_BC) {
throw new InvalidAlgorithmParameterException
("Only supports TrailerFieldBC(1)");
}
int saltLen = params.getSaltLength();
if (this.p11Key != null) {
int maxSaltLen = ((this.p11Key.length() + 7) >> 3) - digestLen.intValue() - 2;
if (DEBUG) {
System.out.println("Max saltLen = " + maxSaltLen);
System.out.println("Curr saltLen = " + saltLen);
}
if (maxSaltLen < 0 || saltLen > maxSaltLen) {
throw new InvalidAlgorithmParameterException("Invalid with current key size");
}
} else {
if (DEBUG) System.out.println("No key available for validating saltLen");
}
// validated, now try to store the parameter internally
try {
this.mechanism.setParameter(
new CK_RSA_PKCS_PSS_PARAMS(digestAlgorithm, "MGF1",
digestAlgorithm, saltLen));
this.sigParams = params;
} catch (IllegalArgumentException iae) {
throw new InvalidAlgorithmParameterException(iae);
}
}
// see JCA spec
@Override
protected void engineInitVerify(PublicKey publicKey)
throws InvalidKeyException {
if (publicKey == null) {
throw new InvalidKeyException("Key must not be null");
}
// Need to check key length whenever a new key is set
if (publicKey != p11Key) {
checkKeySize(publicKey);
}
reset(true);
mode = M_VERIFY;
p11Key = P11KeyFactory.convertKey(token, publicKey, KEY_ALGO);
// For PSS, defer PKCS11 initialization calls to update/doFinal as it
// needs both key and params
}
// see JCA spec
@Override
protected void engineInitSign(PrivateKey privateKey)
throws InvalidKeyException {
if (privateKey == null) {
throw new InvalidKeyException("Key must not be null");
}
// Need to check RSA key length whenever a new key is set
if (privateKey != p11Key) {
checkKeySize(privateKey);
}
reset(true);
mode = M_SIGN;
p11Key = P11KeyFactory.convertKey(token, privateKey, KEY_ALGO);
// For PSS, defer PKCS11 initialization calls to update/doFinal as it
// needs both key and params
}
// see JCA spec
@Override
protected void engineUpdate(byte b) throws SignatureException {
ensureInitialized();
isActive = true;
buffer[0] = b;
engineUpdate(buffer, 0, 1);
}
// see JCA spec
@Override
protected void engineUpdate(byte[] b, int ofs, int len)
throws SignatureException {
ensureInitialized();
if (len == 0) {
return;
}
// check for overflow
if (len + bytesProcessed < 0) {
throw new ProviderException("Processed bytes limits exceeded.");
}
isActive = true;
switch (type) {
case T_UPDATE:
try {
if (mode == M_SIGN) {
System.out.println(this + ": Calling C_SignUpdate");
token.p11.C_SignUpdate(session.id(), 0, b, ofs, len);
} else {
System.out.println(this + ": Calling C_VerfifyUpdate");
token.p11.C_VerifyUpdate(session.id(), 0, b, ofs, len);
}
bytesProcessed += len;
} catch (PKCS11Exception e) {
reset(false);
throw new ProviderException(e);
}
break;
case T_DIGEST:
// should not happen as this should be covered by earlier checks
if (md == null) {
throw new ProviderException("PSS Parameters required");
}
md.update(b, ofs, len);
bytesProcessed += len;
break;
default:
throw new ProviderException("Internal error");
}
}
// see JCA spec
@Override
protected void engineUpdate(ByteBuffer byteBuffer) {
try {
ensureInitialized();
} catch (SignatureException se) {
throw new ProviderException(se);
}
int len = byteBuffer.remaining();
if (len <= 0) {
return;
}
isActive = true;
switch (type) {
case T_UPDATE:
if (byteBuffer instanceof DirectBuffer == false) {
// cannot do better than default impl
super.engineUpdate(byteBuffer);
return;
}
long addr = ((DirectBuffer)byteBuffer).address();
int ofs = byteBuffer.position();
try {
if (mode == M_SIGN) {
System.out.println(this + ": Calling C_SignUpdate");
token.p11.C_SignUpdate
(session.id(), addr + ofs, null, 0, len);
} else {
System.out.println(this + ": Calling C_VerifyUpdate");
token.p11.C_VerifyUpdate
(session.id(), addr + ofs, null, 0, len);
}
bytesProcessed += len;
byteBuffer.position(ofs + len);
} catch (PKCS11Exception e) {
reset(false);
throw new ProviderException("Update failed", e);
}
break;
case T_DIGEST:
// should not happen as this should be covered by earlier checks
if (md == null) {
throw new ProviderException("PSS Parameters required");
}
md.update(byteBuffer);
bytesProcessed += len;
break;
default:
reset(false);
throw new ProviderException("Internal error");
}
}
// see JCA spec
@Override
protected byte[] engineSign() throws SignatureException {
ensureInitialized();
boolean doCancel = true;
if (DEBUG) System.out.print("Generating signature");
try {
byte[] signature;
if (type == T_UPDATE) {
if (DEBUG) System.out.println(" by C_SignFinal");
signature = token.p11.C_SignFinal(session.id(), 0);
} else {
if (md == null) {
throw new ProviderException("PSS Parameters required");
}
byte[] digest = md.digest();
if (DEBUG) System.out.println(" by C_Sign");
signature = token.p11.C_Sign(session.id(), digest);
}
doCancel = false;
return signature;
} catch (PKCS11Exception pe) {
doCancel = false;
throw new ProviderException(pe);
} catch (ProviderException e) {
throw e;
} finally {
reset(doCancel);
}
}
// see JCA spec
@Override
protected boolean engineVerify(byte[] signature) throws SignatureException {
ensureInitialized();
boolean doCancel = true;
if (DEBUG) System.out.print("Verifying signature");
try {
if (type == T_UPDATE) {
if (DEBUG) System.out.println(" by C_VerifyFinal");
token.p11.C_VerifyFinal(session.id(), signature);
} else {
if (md == null) {
throw new ProviderException("PSS Parameters required");
}
byte[] digest = md.digest();
if (DEBUG) System.out.println(" by C_Verify");
token.p11.C_Verify(session.id(), digest, signature);
}
doCancel = false;
return true;
} catch (PKCS11Exception pe) {
doCancel = false;
long errorCode = pe.getErrorCode();
if (errorCode == CKR_SIGNATURE_INVALID) {
return false;
}
if (errorCode == CKR_SIGNATURE_LEN_RANGE) {
// return false rather than throwing an exception
return false;
}
// ECF bug?
if (errorCode == CKR_DATA_LEN_RANGE) {
return false;
}
throw new ProviderException(pe);
} catch (ProviderException e) {
throw e;
} finally {
reset(doCancel);
}
}
// see JCA spec
@SuppressWarnings("deprecation")
@Override
protected void engineSetParameter(String param, Object value)
throws InvalidParameterException {
throw new UnsupportedOperationException("setParameter() not supported");
}
// see JCA spec
@Override
protected void engineSetParameter(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException {
// disallow changing parameters when update has been called
if (isActive) {
throw new ProviderException
("Cannot set parameters during operations");
}
setSigParams(params);
if (type == T_DIGEST) {
try {
this.md = MessageDigest.getInstance(sigParams.getDigestAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new InvalidAlgorithmParameterException(nsae);
}
}
}
// see JCA spec
@SuppressWarnings("deprecation")
@Override
protected Object engineGetParameter(String param)
throws InvalidParameterException {
throw new UnsupportedOperationException("getParameter() not supported");
}
// see JCA spec
@Override
protected AlgorithmParameters engineGetParameters() {
if (this.sigParams != null) {
try {
AlgorithmParameters ap = AlgorithmParameters.getInstance("RSASSA-PSS");
ap.init(this.sigParams);
return ap;
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
return null;
}
}

View File

@ -275,10 +275,10 @@ final class P11RSACipher extends CipherSpi {
long sessId = session.id();
switch (mode) {
case MODE_ENCRYPT:
p11.C_Encrypt(sessId, buffer, 0, inLen, buffer, 0, outLen);
p11.C_Encrypt(sessId, 0, buffer, 0, inLen, 0, buffer, 0, outLen);
break;
case MODE_DECRYPT:
p11.C_Decrypt(sessId, buffer, 0, inLen, buffer, 0, outLen);
p11.C_Decrypt(sessId, 0, buffer, 0, inLen, 0, buffer, 0, outLen);
break;
case MODE_SIGN:
byte[] tmpBuffer = new byte[maxInputSize];
@ -372,11 +372,11 @@ final class P11RSACipher extends CipherSpi {
switch (mode) {
case MODE_ENCRYPT:
n = p11.C_Encrypt
(session.id(), buffer, 0, bufOfs, out, outOfs, outLen);
(session.id(), 0, buffer, 0, bufOfs, 0, out, outOfs, outLen);
break;
case MODE_DECRYPT:
n = p11.C_Decrypt
(session.id(), buffer, 0, bufOfs, out, outOfs, outLen);
(session.id(), 0, buffer, 0, bufOfs, 0, out, outOfs, outLen);
break;
case MODE_SIGN:
byte[] tmpBuffer = new byte[bufOfs];
@ -552,6 +552,7 @@ final class P11RSACipher extends CipherSpi {
s = token.getObjSession();
long p11KeyType =
P11SecretKeyFactory.getPKCS11KeyType(algorithm);
CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] {
new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY),
new CK_ATTRIBUTE(CKA_KEY_TYPE, p11KeyType),

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -516,7 +516,9 @@ public final class SunPKCS11 extends AuthProvider {
String P11SecretKeyFactory = "sun.security.pkcs11.P11SecretKeyFactory";
String P11Cipher = "sun.security.pkcs11.P11Cipher";
String P11RSACipher = "sun.security.pkcs11.P11RSACipher";
String P11AEADCipher = "sun.security.pkcs11.P11AEADCipher";
String P11Signature = "sun.security.pkcs11.P11Signature";
String P11PSSSignature = "sun.security.pkcs11.P11PSSSignature";
// XXX register all aliases
@ -540,6 +542,12 @@ public final class SunPKCS11 extends AuthProvider {
d(MD, "SHA-512", P11Digest,
s("2.16.840.1.101.3.4.2.3", "OID.2.16.840.1.101.3.4.2.3"),
m(CKM_SHA512));
d(MD, "SHA-512/224", P11Digest,
s("2.16.840.1.101.3.4.2.5", "OID.2.16.840.1.101.3.4.2.5"),
m(CKM_SHA512_224));
d(MD, "SHA-512/256", P11Digest,
s("2.16.840.1.101.3.4.2.6", "OID.2.16.840.1.101.3.4.2.6"),
m(CKM_SHA512_256));
d(MAC, "HmacMD5", P11MAC,
m(CKM_MD5_HMAC));
@ -558,13 +566,22 @@ public final class SunPKCS11 extends AuthProvider {
d(MAC, "HmacSHA512", P11MAC,
s("1.2.840.113549.2.11", "OID.1.2.840.113549.2.11"),
m(CKM_SHA512_HMAC));
d(MAC, "HmacSHA512/224", P11MAC,
s("1.2.840.113549.2.12", "OID.1.2.840.113549.2.12"),
m(CKM_SHA512_224_HMAC));
d(MAC, "HmacSHA512/256", P11MAC,
s("1.2.840.113549.2.13", "OID.1.2.840.113549.2.13"),
m(CKM_SHA512_256_HMAC));
d(MAC, "SslMacMD5", P11MAC,
m(CKM_SSL3_MD5_MAC));
d(MAC, "SslMacSHA1", P11MAC,
m(CKM_SSL3_SHA1_MAC));
d(KPG, "RSA", P11KeyPairGenerator,
s("1.2.840.113549.1.1", "OID.1.2.840.113549.1.1"),
m(CKM_RSA_PKCS_KEY_PAIR_GEN));
d(KPG, "DSA", P11KeyPairGenerator,
s("1.3.14.3.2.12", "1.2.840.10040.4.1", "OID.1.2.840.10040.4.1"),
m(CKM_DSA_KEY_PAIR_GEN));
@ -587,6 +604,7 @@ public final class SunPKCS11 extends AuthProvider {
// register (Secret)KeyFactories if there are any mechanisms
// for a particular algorithm that we support
d(KF, "RSA", P11RSAKeyFactory,
s("1.2.840.113549.1.1", "OID.1.2.840.113549.1.1"),
m(CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS, CKM_RSA_X_509));
d(KF, "DSA", P11DSAKeyFactory,
s("1.3.14.3.2.12", "1.2.840.10040.4.1", "OID.1.2.840.10040.4.1"),
@ -600,10 +618,14 @@ public final class SunPKCS11 extends AuthProvider {
// AlgorithmParameters for EC.
// Only needed until we have an EC implementation in the SUN provider.
d(AGP, "EC", "sun.security.util.ECParameters",
s("1.2.840.10045.2.1"),
s("1.2.840.10045.2.1"),
m(CKM_EC_KEY_PAIR_GEN, CKM_ECDH1_DERIVE,
CKM_ECDSA, CKM_ECDSA_SHA1));
d(AGP, "GCM", "sun.security.util.GCMParameters",
m(CKM_AES_GCM));
d(KA, "DH", P11KeyAgreement, s("DiffieHellman"),
m(CKM_DH_PKCS_DERIVE));
d(KA, "ECDH", "sun.security.pkcs11.P11ECDHKeyAgreement",
@ -669,12 +691,24 @@ public final class SunPKCS11 extends AuthProvider {
m(CKM_AES_ECB));
d(CIP, "AES/CTR/NoPadding", P11Cipher,
m(CKM_AES_CTR));
d(CIP, "AES/GCM/NoPadding", P11AEADCipher,
m(CKM_AES_GCM));
d(CIP, "AES_128/GCM/NoPadding", P11AEADCipher,
s("2.16.840.1.101.3.4.1.6", "OID.2.16.840.1.101.3.4.1.6"),
m(CKM_AES_GCM));
d(CIP, "AES_192/GCM/NoPadding", P11AEADCipher,
s("2.16.840.1.101.3.4.1.26", "OID.2.16.840.1.101.3.4.1.26"),
m(CKM_AES_GCM));
d(CIP, "AES_256/GCM/NoPadding", P11AEADCipher,
s("2.16.840.1.101.3.4.1.46", "OID.2.16.840.1.101.3.4.1.46"),
m(CKM_AES_GCM));
d(CIP, "Blowfish/CBC/NoPadding", P11Cipher,
m(CKM_BLOWFISH_CBC));
d(CIP, "Blowfish/CBC/PKCS5Padding", P11Cipher,
m(CKM_BLOWFISH_CBC));
// XXX RSA_X_509, RSA_OAEP not yet supported
d(CIP, "RSA/ECB/PKCS1Padding", P11RSACipher, s("RSA"),
m(CKM_RSA_PKCS));
d(CIP, "RSA/ECB/NoPadding", P11RSACipher,
@ -686,12 +720,25 @@ public final class SunPKCS11 extends AuthProvider {
s("SHA1withDSA", "1.3.14.3.2.13", "1.3.14.3.2.27",
"1.2.840.10040.4.3", "OID.1.2.840.10040.4.3"),
m(CKM_DSA_SHA1, CKM_DSA));
d(SIG, "SHA224withDSA", P11Signature,
s("2.16.840.1.101.3.4.3.1", "OID.2.16.840.1.101.3.4.3.1"),
m(CKM_DSA_SHA224));
d(SIG, "SHA256withDSA", P11Signature,
s("2.16.840.1.101.3.4.3.2", "OID.2.16.840.1.101.3.4.3.2"),
m(CKM_DSA_SHA256));
d(SIG, "SHA384withDSA", P11Signature,
s("2.16.840.1.101.3.4.3.3", "OID.2.16.840.1.101.3.4.3.3"),
m(CKM_DSA_SHA384));
d(SIG, "SHA512withDSA", P11Signature,
s("2.16.840.1.101.3.4.3.4", "OID.2.16.840.1.101.3.4.3.4"),
m(CKM_DSA_SHA512));
d(SIG, "RawDSAinP1363Format", P11Signature,
s("NONEwithDSAinP1363Format"),
m(CKM_DSA));
d(SIG, "DSAinP1363Format", P11Signature,
s("SHA1withDSAinP1363Format"),
m(CKM_DSA_SHA1, CKM_DSA));
d(SIG, "NONEwithECDSA", P11Signature,
m(CKM_ECDSA));
d(SIG, "SHA1withECDSA", P11Signature,
@ -743,6 +790,19 @@ public final class SunPKCS11 extends AuthProvider {
d(SIG, "SHA512withRSA", P11Signature,
s("1.2.840.113549.1.1.13", "OID.1.2.840.113549.1.1.13"),
m(CKM_SHA512_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
d(SIG, "RSASSA-PSS", P11PSSSignature,
s("1.2.840.113549.1.1.10", "OID.1.2.840.113549.1.1.10"),
m(CKM_RSA_PKCS_PSS));
d(SIG, "SHA1withRSASSA-PSS", P11PSSSignature,
m(CKM_SHA1_RSA_PKCS_PSS));
d(SIG, "SHA224withRSASSA-PSS", P11PSSSignature,
m(CKM_SHA224_RSA_PKCS_PSS));
d(SIG, "SHA256withRSASSA-PSS", P11PSSSignature,
m(CKM_SHA256_RSA_PKCS_PSS));
d(SIG, "SHA384withRSASSA-PSS", P11PSSSignature,
m(CKM_SHA384_RSA_PKCS_PSS));
d(SIG, "SHA512withRSASSA-PSS", P11PSSSignature,
m(CKM_SHA512_RSA_PKCS_PSS));
d(KG, "SunTlsRsaPremasterSecret",
"sun.security.pkcs11.P11TlsRsaPremasterSecretGenerator",
@ -1008,11 +1068,17 @@ public final class SunPKCS11 extends AuthProvider {
} else if (type == CIP) {
if (algorithm.startsWith("RSA")) {
return new P11RSACipher(token, algorithm, mechanism);
} else if (algorithm.endsWith("GCM/NoPadding")) {
return new P11AEADCipher(token, algorithm, mechanism);
} else {
return new P11Cipher(token, algorithm, mechanism);
}
} else if (type == SIG) {
return new P11Signature(token, algorithm, mechanism);
if (algorithm.indexOf("RSASSA-PSS") != -1) {
return new P11PSSSignature(token, algorithm, mechanism);
} else {
return new P11Signature(token, algorithm, mechanism);
}
} else if (type == MAC) {
return new P11Mac(token, algorithm, mechanism);
} else if (type == KPG) {
@ -1051,7 +1117,14 @@ public final class SunPKCS11 extends AuthProvider {
} else if (type == KS) {
return token.getKeyStore();
} else if (type == AGP) {
return new sun.security.util.ECParameters();
if (algorithm == "EC") {
return new sun.security.util.ECParameters();
} else if (algorithm == "GCM") {
return new sun.security.util.GCMParameters();
} else {
throw new NoSuchAlgorithmException("Unsupported algorithm: "
+ algorithm);
}
} else {
throw new NoSuchAlgorithmException("Unknown type: " + type);
}
@ -1070,7 +1143,7 @@ public final class SunPKCS11 extends AuthProvider {
String keyAlgorithm = key.getAlgorithm();
// RSA signatures and cipher
if (((type == CIP) && algorithm.startsWith("RSA"))
|| (type == SIG) && algorithm.endsWith("RSA")) {
|| (type == SIG) && (algorithm.indexOf("RSA") != -1)) {
if (keyAlgorithm.equals("RSA") == false) {
return false;
}

View File

@ -0,0 +1,83 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.pkcs11.wrapper;
/**
* This class represents the necessary parameters required by
* the CKM_AES_CCM mechanism as defined in CK_CCM_PARAMS structure.<p>
* <B>PKCS#11 structure:</B>
* <PRE>
* typedef struct CK_CCM_PARAMS {
* CK_ULONG ulDataLen;
* CK_BYTE_PTR pNonce;
* CK_ULONG ulNonceLen;
* CK_BYTE_PTR pAAD;
* CK_ULONG ulAADLen;
* CK_ULONG ulMACLen;
* } CK_CCM_PARAMS;
* </PRE>
*
* @since 13
*/
public class CK_CCM_PARAMS {
private final long dataLen;
private final byte[] nonce;
private final byte[] aad;
private final long macLen;
public CK_CCM_PARAMS(int tagLen, byte[] iv, byte[] aad, int dataLen) {
this.dataLen = dataLen;
this.nonce = iv;
this.aad = aad;
this.macLen = tagLen;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(Constants.INDENT);
sb.append("ulDataLen: ");
sb.append(dataLen);
sb.append(Constants.NEWLINE);
sb.append(Constants.INDENT);
sb.append("iv: ");
sb.append(Functions.toHexString(nonce));
sb.append(Constants.NEWLINE);
sb.append(Constants.INDENT);
sb.append("aad: ");
sb.append(Functions.toHexString(aad));
sb.append(Constants.NEWLINE);
sb.append(Constants.INDENT);
sb.append("tagLen: ");
sb.append(macLen);
return sb.toString();
}
}

View File

@ -0,0 +1,75 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.pkcs11.wrapper;
/**
* This class represents the necessary parameters required by
* the CKM_AES_GCM mechanism as defined in CK_GCM_PARAMS structure.<p>
* <B>PKCS#11 structure:</B>
* <PRE>
* typedef struct CK_GCM_PARAMS {
* CK_BYTE_PTR pIv;
* CK_ULONG ulIvLen;
* CK_BYTE_PTR pAAD;
* CK_ULONG ulAADLen;
* CK_ULONG ulTagBits;
* } CK_GCM_PARAMS;
* </PRE>
*
* @since 10
*/
public class CK_GCM_PARAMS {
private final byte[] iv;
private final byte[] aad;
private final long tagBits;
public CK_GCM_PARAMS(int tagLenInBits, byte[] iv, byte[] aad) {
this.iv = iv;
this.aad = aad;
this.tagBits = tagLenInBits;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(Constants.INDENT);
sb.append("iv: ");
sb.append(Functions.toHexString(iv));
sb.append(Constants.NEWLINE);
sb.append(Constants.INDENT);
sb.append("aad: ");
sb.append(Functions.toHexString(aad));
sb.append(Constants.NEWLINE);
sb.append(Constants.INDENT);
sb.append("tagLen(in bits): ");
sb.append(tagBits);
return sb.toString();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@ -82,11 +82,15 @@ public class CK_MECHANISM {
* CK_ULONG ulParameterLen;
* </PRE>
*/
public Object pParameter;
public Object pParameter = null;
public CK_MECHANISM() {
// empty
}
// pointer to native CK_MECHANISM structure
// For mechanisms which have only mechanism id, the native structure
// can be freed right after init and this field will not be used. However,
// for mechanisms which have both mechanism id and parameters, it can
// only be freed after operation is finished. Thus, the native pointer
// will be stored here and then be explicitly freed by caller.
private long pHandle = 0L;
public CK_MECHANISM(long mechanism) {
this.mechanism = mechanism;
@ -95,7 +99,6 @@ public class CK_MECHANISM {
// We don't have a (long,Object) constructor to force type checking.
// This makes sure we don't accidentally pass a class that the native
// code cannot handle.
public CK_MECHANISM(long mechanism, byte[] pParameter) {
init(mechanism, pParameter);
}
@ -144,6 +147,33 @@ public class CK_MECHANISM {
init(mechanism, params);
}
public CK_MECHANISM(long mechanism, CK_GCM_PARAMS params) {
init(mechanism, params);
}
public CK_MECHANISM(long mechanism, CK_CCM_PARAMS params) {
init(mechanism, params);
}
// For PSS. the parameter may be set multiple times, use the
// CK_MECHANISM(long) constructor and setParameter(CK_RSA_PKCS_PSS_PARAMS)
// methods instead of creating yet another constructor
public void setParameter(CK_RSA_PKCS_PSS_PARAMS params) {
assert(this.mechanism == CKM_RSA_PKCS_PSS);
assert(params != null);
if (this.pParameter != null && this.pParameter.equals(params)) {
return;
}
freeHandle();
this.pParameter = params;
}
public void freeHandle() {
if (this.pHandle != 0L) {
this.pHandle = PKCS11.freeMechanism(pHandle);
}
}
private void init(long mechanism, Object pParameter) {
this.mechanism = mechanism;
this.pParameter = pParameter;
@ -167,12 +197,17 @@ public class CK_MECHANISM {
sb.append(pParameter.toString());
sb.append(Constants.NEWLINE);
/*
sb.append(Constants.INDENT);
sb.append("ulParameterLen: ??");
//buffer.append(pParameter.length);
//buffer.append(Constants.NEWLINE);
sb.append(Constants.NEWLINE);
*/
if (pHandle != 0L) {
sb.append(Constants.INDENT);
sb.append("pHandle: ");
sb.append(pHandle);
sb.append(Constants.NEWLINE);
}
return sb.toString() ;
}
}

View File

@ -1,118 +1,105 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment:
*
* "This product includes software developed by IAIK of Graz University of
* Technology."
*
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Graz University of Technology" and "IAIK of Graz University of
* Technology" must not be used to endorse or promote products derived from
* this software without prior written permission.
*
* 5. Products derived from this software may not be called
* "IAIK PKCS Wrapper", nor may "IAIK" appear in their name, without prior
* written permission of Graz University of Technology.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE LICENSOR BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.pkcs11.wrapper;
import java.security.ProviderException;
import java.security.spec.PSSParameterSpec;
import java.security.spec.MGF1ParameterSpec;
/**
* class CK_RSA_PKCS_PSS_PARAMS provides the parameters to the CKM_RSA_PKCS_OAEP
* mechanism.<p>
* This class represents the necessary parameters required by the
* CKM_RSA_PKCS_PSS mechanism as defined in CK_RSA_PKCS_PSS_PARAMS structure.<p>
* <B>PKCS#11 structure:</B>
* <PRE>
* typedef struct CK_RSA_PKCS_PSS_PARAMS {
* CK_MECHANISM_TYPE hashAlg;
* CK_RSA_PKCS_MGF_TYPE mgf;
* CK_ULONG sLen;
* CK_MECHANISM_TYPE hashAlg;
* CK_RSA_PKCS_MGF_TYPE mgf;
* CK_ULONG sLen;
* } CK_RSA_PKCS_PSS_PARAMS;
* </PRE>
*
* @author Karl Scheibelhofer <Karl.Scheibelhofer@iaik.at>
* @since 13
*/
public class CK_RSA_PKCS_PSS_PARAMS {
/**
* <B>PKCS#11:</B>
* <PRE>
* CK_MECHANISM_TYPE hashAlg;
* </PRE>
*/
public long hashAlg;
private final long hashAlg;
private final long mgf;
private final long sLen;
/**
* <B>PKCS#11:</B>
* <PRE>
* CK_RSA_PKCS_MGF_TYPE mgf;
* </PRE>
*/
public long mgf;
public CK_RSA_PKCS_PSS_PARAMS(String hashAlg, String mgfAlg,
String mgfHash, int sLen) {
this.hashAlg = Functions.getHashMechId(hashAlg);
if (!mgfAlg.equals("MGF1")) {
throw new ProviderException("Only MGF1 is supported");
}
// no dash in PKCS#11 mechanism names
this.mgf = Functions.getMGFId("CKG_MGF1_" + hashAlg.replaceFirst("-", ""));
this.sLen = sLen;
}
/**
* <B>PKCS#11:</B>
* <PRE>
* CK_ULONG sLen;
* </PRE>
*/
public long sLen;
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
/**
* Returns the string representation of CK_PKCS5_PBKD2_PARAMS.
*
* @return the string representation of CK_PKCS5_PBKD2_PARAMS
*/
if (!(o instanceof CK_RSA_PKCS_PSS_PARAMS)) {
return false;
}
CK_RSA_PKCS_PSS_PARAMS other = (CK_RSA_PKCS_PSS_PARAMS) o;
return ((other.hashAlg == hashAlg) &&
(other.mgf == mgf) &&
(other.sLen == sLen));
}
@Override
public int hashCode() {
return (int)(hashAlg << 2 + mgf << 1 + sLen);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(Constants.INDENT);
sb.append("hashAlg: 0x");
sb.append("hashAlg: ");
sb.append(Functions.toFullHexString(hashAlg));
sb.append(Constants.NEWLINE);
sb.append(Constants.INDENT);
sb.append("mgf: 0x");
sb.append("mgf: ");
sb.append(Functions.toFullHexString(mgf));
sb.append(Constants.NEWLINE);
sb.append(Constants.INDENT);
sb.append("sLen: ");
sb.append("sLen(in bytes): ");
sb.append(sLen);
//buffer.append(Constants.NEWLINE);
return sb.toString();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@ -97,6 +97,13 @@ public class Functions {
private static final Map<String,Integer> objectClassIds =
new HashMap<String,Integer>();
// MGFs (CKG_*)
private static final Map<Integer,String> mgfNames =
new HashMap<Integer,String>();
private static final Map<String,Integer> mgfIds =
new HashMap<String,Integer>();
/**
* For converting numbers to their hex presentation.
*/
@ -401,7 +408,11 @@ public class Functions {
name = nameMap.get(Integer.valueOf((int)id));
}
if (name == null) {
name = "Unknown 0x" + toFullHexString(id);
if ((id & CKM_VENDOR_DEFINED) != 0) {
name = "(Vendor-Specific) 0x" + toFullHexString(id);
} else {
name = "(Unknown) 0x" + toFullHexString(id);
}
}
return name;
}
@ -450,6 +461,14 @@ public class Functions {
return hashMechIds.get(name);
}
public static String getMGFName(long id) {
return getName(mgfNames, id);
}
public static long getMGFId(String name) {
return getId(mgfIds, name);
}
/**
* Check the given arrays for equalitiy. This method considers both arrays as
* equal, if both are <code>null</code> or both have the same length and
@ -595,8 +614,14 @@ public class Functions {
addMapping(objectClassNames, objectClassIds, id, name);
}
private static void addHashMech(long id, String name) {
hashMechIds.put(name, id);
private static void addHashMech(long id, String... names) {
for (String n : names) {
hashMechIds.put(n, id);
}
}
private static void addMGF(long id, String name) {
addMapping(mgfNames, mgfIds, id, name);
}
static {
@ -618,16 +643,27 @@ public class Functions {
addMech(CKM_DSA_KEY_PAIR_GEN, "CKM_DSA_KEY_PAIR_GEN");
addMech(CKM_DSA, "CKM_DSA");
addMech(CKM_DSA_SHA1, "CKM_DSA_SHA1");
addMech(CKM_DSA_SHA224, "CKM_DSA_SHA224");
addMech(CKM_DSA_SHA256, "CKM_DSA_SHA256");
addMech(CKM_DSA_SHA384, "CKM_DSA_SHA384");
addMech(CKM_DSA_SHA512, "CKM_DSA_SHA512");
addMech(CKM_DH_PKCS_KEY_PAIR_GEN, "CKM_DH_PKCS_KEY_PAIR_GEN");
addMech(CKM_DH_PKCS_DERIVE, "CKM_DH_PKCS_DERIVE");
addMech(CKM_X9_42_DH_KEY_PAIR_GEN, "CKM_X9_42_DH_KEY_PAIR_GEN");
addMech(CKM_X9_42_DH_DERIVE, "CKM_X9_42_DH_DERIVE");
addMech(CKM_X9_42_DH_HYBRID_DERIVE, "CKM_X9_42_DH_HYBRID_DERIVE");
addMech(CKM_X9_42_MQV_DERIVE, "CKM_X9_42_MQV_DERIVE");
addMech(CKM_SHA224_RSA_PKCS, "CKM_SHA224_RSA_PKCS");
addMech(CKM_SHA256_RSA_PKCS, "CKM_SHA256_RSA_PKCS");
addMech(CKM_SHA384_RSA_PKCS, "CKM_SHA384_RSA_PKCS");
addMech(CKM_SHA512_RSA_PKCS, "CKM_SHA512_RSA_PKCS");
addMech(CKM_SHA256_RSA_PKCS_PSS, "CKM_SHA256_RSA_PKCS_PSS");
addMech(CKM_SHA384_RSA_PKCS_PSS, "CKM_SHA384_RSA_PKCS_PSS");
addMech(CKM_SHA512_RSA_PKCS_PSS, "CKM_SHA512_RSA_PKCS_PSS");
addMech(CKM_SHA224_RSA_PKCS, "CKM_SHA224_RSA_PKCS");
addMech(CKM_SHA224_RSA_PKCS_PSS, "CKM_SHA224_RSA_PKCS_PSS");
addMech(CKM_RC2_KEY_GEN, "CKM_RC2_KEY_GEN");
addMech(CKM_RC2_ECB, "CKM_RC2_ECB");
addMech(CKM_RC2_CBC, "CKM_RC2_CBC");
@ -649,12 +685,21 @@ public class Functions {
addMech(CKM_DES3_MAC, "CKM_DES3_MAC");
addMech(CKM_DES3_MAC_GENERAL, "CKM_DES3_MAC_GENERAL");
addMech(CKM_DES3_CBC_PAD, "CKM_DES3_CBC_PAD");
addMech(CKM_DES3_CMAC_GENERAL, "CKM_DES3_CMAC_GENERAL");
addMech(CKM_DES3_CMAC, "CKM_DES3_CMAC");
addMech(CKM_CDMF_KEY_GEN, "CKM_CDMF_KEY_GEN");
addMech(CKM_CDMF_ECB, "CKM_CDMF_ECB");
addMech(CKM_CDMF_CBC, "CKM_CDMF_CBC");
addMech(CKM_CDMF_MAC, "CKM_CDMF_MAC");
addMech(CKM_CDMF_MAC_GENERAL, "CKM_CDMF_MAC_GENERAL");
addMech(CKM_CDMF_CBC_PAD, "CKM_CDMF_CBC_PAD");
addMech(CKM_DES_OFB64, "CKM_DES_OFB64");
addMech(CKM_DES_OFB8, "CKM_DES_OFB8");
addMech(CKM_DES_CFB64, "CKM_DES_CFB64");
addMech(CKM_DES_CFB8, "CKM_DES_CFB8");
addMech(CKM_MD2, "CKM_MD2");
addMech(CKM_MD2_HMAC, "CKM_MD2_HMAC");
addMech(CKM_MD2_HMAC_GENERAL, "CKM_MD2_HMAC_GENERAL");
@ -682,6 +727,26 @@ public class Functions {
addMech(CKM_SHA512, "CKM_SHA512");
addMech(CKM_SHA512_HMAC, "CKM_SHA512_HMAC");
addMech(CKM_SHA512_HMAC_GENERAL, "CKM_SHA512_HMAC_GENERAL");
addMech(CKM_SHA512_224, "CKM_SHA512_224");
addMech(CKM_SHA512_224_HMAC, "CKM_SHA512_224_HMAC");
addMech(CKM_SHA512_224_HMAC_GENERAL, "CKM_SHA512_224_HMAC_GENERAL");
addMech(CKM_SHA512_224_KEY_DERIVATION, "CKM_SHA512_224_KEY_DERIVATION");
addMech(CKM_SHA512_256, "CKM_SHA512_256");
addMech(CKM_SHA512_256_HMAC, "CKM_SHA512_256_HMAC");
addMech(CKM_SHA512_256_HMAC_GENERAL, "CKM_SHA512_256_HMAC_GENERAL");
addMech(CKM_SHA512_256_KEY_DERIVATION, "CKM_SHA512_256_KEY_DERIVATION");
addMech(CKM_SHA512_T, "CKM_SHA512_T");
addMech(CKM_SHA512_T_HMAC, "CKM_SHA512_T_HMAC");
addMech(CKM_SHA512_T_HMAC_GENERAL, "CKM_SHA512_T_HMAC_GENERAL");
addMech(CKM_SHA512_T_KEY_DERIVATION, "CKM_SHA512_T_KEY_DERIVATION");
addMech(CKM_SECURID_KEY_GEN, "CKM_SECURID_KEY_GEN");
addMech(CKM_SECURID, "CKM_SECURID");
addMech(CKM_HOTP_KEY_GEN, "CKM_HOTP_KEY_GEN");
addMech(CKM_HOTP, "CKM_HOTP");
addMech(CKM_ACTI, "CKM_ACTI");
addMech(CKM_ACTI_KEY_GEN, "CKM_ACTI_KEY_GEN");
addMech(CKM_CAST_KEY_GEN, "CKM_CAST_KEY_GEN");
addMech(CKM_CAST_ECB, "CKM_CAST_ECB");
addMech(CKM_CAST_CBC, "CKM_CAST_CBC");
@ -729,10 +794,7 @@ public class Functions {
addMech(CKM_TLS_PRF, "CKM_TLS_PRF");
addMech(CKM_SSL3_MD5_MAC, "CKM_SSL3_MD5_MAC");
addMech(CKM_SSL3_SHA1_MAC, "CKM_SSL3_SHA1_MAC");
addMech(CKM_TLS12_MASTER_KEY_DERIVE, "CKM_TLS12_MASTER_KEY_DERIVE");
addMech(CKM_TLS12_KEY_AND_MAC_DERIVE, "CKM_TLS12_KEY_AND_MAC_DERIVE");
addMech(CKM_TLS12_MASTER_KEY_DERIVE_DH, "CKM_TLS12_MASTER_KEY_DERIVE_DH");
addMech(CKM_TLS_MAC, "CKM_TLS_MAC");
addMech(CKM_MD5_KEY_DERIVATION, "CKM_MD5_KEY_DERIVATION");
addMech(CKM_MD2_KEY_DERIVATION, "CKM_MD2_KEY_DERIVATION");
addMech(CKM_SHA1_KEY_DERIVATION, "CKM_SHA1_KEY_DERIVATION");
@ -754,8 +816,62 @@ public class Functions {
addMech(CKM_PBE_SHA1_RC2_40_CBC, "CKM_PBE_SHA1_RC2_40_CBC");
addMech(CKM_PKCS5_PBKD2, "CKM_PKCS5_PBKD2");
addMech(CKM_PBA_SHA1_WITH_SHA1_HMAC, "CKM_PBA_SHA1_WITH_SHA1_HMAC");
addMech(CKM_WTLS_PRE_MASTER_KEY_GEN, "CKM_WTLS_PRE_MASTER_KEY_GEN");
addMech(CKM_WTLS_MASTER_KEY_DERIVE, "CKM_WTLS_MASTER_KEY_DERIVE");
addMech(CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC,
"CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC");
addMech(CKM_WTLS_PRF, "CKM_WTLS_PRF");
addMech(CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE,
"CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE");
addMech(CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE,
"CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE");
addMech(CKM_TLS10_MAC_SERVER, "CKM_TLS10_MAC_SERVER");
addMech(CKM_TLS10_MAC_CLIENT, "CKM_TLS10_MAC_CLIENT");
addMech(CKM_TLS12_MAC, "CKM_TLS12_MAC");
addMech(CKM_TLS12_KDF, "CKM_TLS12_KDF");
addMech(CKM_TLS12_MASTER_KEY_DERIVE, "CKM_TLS12_MASTER_KEY_DERIVE");
addMech(CKM_TLS12_KEY_AND_MAC_DERIVE, "CKM_TLS12_KEY_AND_MAC_DERIVE");
addMech(CKM_TLS12_MASTER_KEY_DERIVE_DH, "CKM_TLS12_MASTER_KEY_DERIVE_DH");
addMech(CKM_TLS12_KEY_SAFE_DERIVE, "CKM_TLS12_KEY_SAFE_DERIVE");
addMech(CKM_TLS_MAC, "CKM_TLS_MAC");
addMech(CKM_TLS_KDF, "CKM_TLS_KDF");
addMech(CKM_KEY_WRAP_LYNKS, "CKM_KEY_WRAP_LYNKS");
addMech(CKM_KEY_WRAP_SET_OAEP, "CKM_KEY_WRAP_SET_OAEP");
addMech(CKM_CMS_SIG, "CKM_CMS_SIG");
addMech(CKM_KIP_DERIVE, "CKM_KIP_DERIVE");
addMech(CKM_KIP_WRAP, "CKM_KIP_WRAP");
addMech(CKM_KIP_MAC, "CKM_KIP_MAC");
addMech(CKM_CAMELLIA_KEY_GEN, "CKM_CAMELLIA_KEY_GEN");
addMech(CKM_CAMELLIA_ECB, "CKM_CAMELLIA_ECB");
addMech(CKM_CAMELLIA_CBC, "CKM_CAMELLIA_CBC");
addMech(CKM_CAMELLIA_MAC, "CKM_CAMELLIA_MAC");
addMech(CKM_CAMELLIA_MAC_GENERAL, "CKM_CAMELLIA_MAC_GENERAL");
addMech(CKM_CAMELLIA_CBC_PAD, "CKM_CAMELLIA_CBC_PAD");
addMech(CKM_CAMELLIA_ECB_ENCRYPT_DATA, "CKM_CAMELLIA_ECB_ENCRYPT_DATA");
addMech(CKM_CAMELLIA_CBC_ENCRYPT_DATA, "CKM_CAMELLIA_CBC_ENCRYPT_DATA");
addMech(CKM_CAMELLIA_CTR, "CKM_CAMELLIA_CTR");
addMech(CKM_ARIA_KEY_GEN, "CKM_ARIA_KEY_GEN");
addMech(CKM_ARIA_ECB, "CKM_ARIA_ECB");
addMech(CKM_ARIA_CBC, "CKM_ARIA_CBC");
addMech(CKM_ARIA_MAC, "CKM_ARIA_MAC");
addMech(CKM_ARIA_MAC_GENERAL, "CKM_ARIA_MAC_GENERAL");
addMech(CKM_ARIA_CBC_PAD, "CKM_ARIA_CBC_PAD");
addMech(CKM_ARIA_ECB_ENCRYPT_DATA, "CKM_ARIA_ECB_ENCRYPT_DATA");
addMech(CKM_ARIA_CBC_ENCRYPT_DATA, "CKM_ARIA_CBC_ENCRYPT_DATA");
addMech(CKM_SEED_KEY_GEN, "CKM_SEED_KEY_GEN");
addMech(CKM_SEED_ECB, "CKM_SEED_ECB");
addMech(CKM_SEED_CBC, "CKM_SEED_CBC");
addMech(CKM_SEED_MAC, "CKM_SEED_MAC");
addMech(CKM_SEED_MAC_GENERAL, "CKM_SEED_MAC_GENERAL");
addMech(CKM_SEED_CBC_PAD, "CKM_SEED_CBC_PAD");
addMech(CKM_SEED_ECB_ENCRYPT_DATA, "CKM_SEED_ECB_ENCRYPT_DATA");
addMech(CKM_SEED_CBC_ENCRYPT_DATA, "CKM_SEED_CBC_ENCRYPT_DATA");
addMech(CKM_SKIPJACK_KEY_GEN, "CKM_SKIPJACK_KEY_GEN");
addMech(CKM_SKIPJACK_ECB64, "CKM_SKIPJACK_ECB64");
addMech(CKM_SKIPJACK_CBC64, "CKM_SKIPJACK_CBC64");
@ -780,9 +896,17 @@ public class Functions {
addMech(CKM_EC_KEY_PAIR_GEN, "CKM_EC_KEY_PAIR_GEN");
addMech(CKM_ECDSA, "CKM_ECDSA");
addMech(CKM_ECDSA_SHA1, "CKM_ECDSA_SHA1");
addMech(CKM_ECDSA_SHA224, "CKM_ECDSA_SHA224");
addMech(CKM_ECDSA_SHA256, "CKM_ECDSA_SHA256");
addMech(CKM_ECDSA_SHA384, "CKM_ECDSA_SHA384");
addMech(CKM_ECDSA_SHA512, "CKM_ECDSA_SHA512");
addMech(CKM_ECDH1_DERIVE, "CKM_ECDH1_DERIVE");
addMech(CKM_ECDH1_COFACTOR_DERIVE, "CKM_ECDH1_COFACTOR_DERIVE");
addMech(CKM_ECMQV_DERIVE, "CKM_ECMQV_DERIVE");
addMech(CKM_ECDH_AES_KEY_WRAP, "CKM_ECDH_AES_KEY_WRAP");
addMech(CKM_RSA_AES_KEY_WRAP, "CKM_RSA_AES_KEY_WRAP");
addMech(CKM_JUNIPER_KEY_GEN, "CKM_JUNIPER_KEY_GEN");
addMech(CKM_JUNIPER_ECB128, "CKM_JUNIPER_ECB128");
addMech(CKM_JUNIPER_CBC128, "CKM_JUNIPER_CBC128");
@ -796,11 +920,61 @@ public class Functions {
addMech(CKM_AES_MAC, "CKM_AES_MAC");
addMech(CKM_AES_MAC_GENERAL, "CKM_AES_MAC_GENERAL");
addMech(CKM_AES_CBC_PAD, "CKM_AES_CBC_PAD");
addMech(CKM_AES_CTR, "CKM_AES_CTR");
addMech(CKM_AES_GCM, "CKM_AES_GCM");
addMech(CKM_AES_CCM, "CKM_AES_CCM");
addMech(CKM_AES_CTS, "CKM_AES_CTS");
addMech(CKM_AES_CMAC, "CKM_AES_CMAC");
addMech(CKM_AES_CMAC_GENERAL, "CKM_AES_CMAC_GENERAL");
addMech(CKM_AES_XCBC_MAC, "CKM_AES_XCBC_MAC");
addMech(CKM_AES_XCBC_MAC_96, "CKM_AES_XCBC_MAC_96");
addMech(CKM_AES_GMAC, "CKM_AES_GMAC");
addMech(CKM_BLOWFISH_KEY_GEN, "CKM_BLOWFISH_KEY_GEN");
addMech(CKM_BLOWFISH_CBC, "CKM_BLOWFISH_CBC");
addMech(CKM_TWOFISH_KEY_GEN, "CKM_TWOFISH_KEY_GEN");
addMech(CKM_TWOFISH_CBC, "CKM_TWOFISH_CBC");
addMech(CKM_BLOWFISH_CBC_PAD, "CKM_BLOWFISH_CBC_PAD");
addMech(CKM_TWOFISH_CBC_PAD, "CKM_TWOFISH_CBC_PAD");
addMech(CKM_DES_ECB_ENCRYPT_DATA, "CKM_DES_ECB_ENCRYPT_DATA");
addMech(CKM_DES_CBC_ENCRYPT_DATA, "CKM_DES_CBC_ENCRYPT_DATA");
addMech(CKM_DES3_ECB_ENCRYPT_DATA, "CKM_DES3_ECB_ENCRYPT_DATA");
addMech(CKM_DES3_CBC_ENCRYPT_DATA, "CKM_DES3_CBC_ENCRYPT_DATA");
addMech(CKM_AES_ECB_ENCRYPT_DATA, "CKM_AES_ECB_ENCRYPT_DATA");
addMech(CKM_AES_CBC_ENCRYPT_DATA, "CKM_AES_CBC_ENCRYPT_DATA");
addMech(CKM_GOSTR3410_KEY_PAIR_GEN, "CKM_GOSTR3410_KEY_PAIR_GEN");
addMech(CKM_GOSTR3410, "CKM_GOSTR3410");
addMech(CKM_GOSTR3410_WITH_GOSTR3411, "CKM_GOSTR3410_WITH_GOSTR3411");
addMech(CKM_GOSTR3410_KEY_WRAP, "CKM_GOSTR3410_KEY_WRAP");
addMech(CKM_GOSTR3410_DERIVE, "CKM_GOSTR3410_DERIVE");
addMech(CKM_GOSTR3411, "CKM_GOSTR3411");
addMech(CKM_GOSTR3411_HMAC, "CKM_GOSTR3411_HMAC");
addMech(CKM_GOST28147_KEY_GEN, "CKM_GOST28147_KEY_GEN");
addMech(CKM_GOST28147_ECB, "CKM_GOST28147_ECB");
addMech(CKM_GOST28147, "CKM_GOST28147");
addMech(CKM_GOST28147_MAC, "CKM_GOST28147_MAC");
addMech(CKM_GOST28147_KEY_WRAP, "CKM_GOST28147_KEY_WRAP");
addMech(CKM_DSA_PARAMETER_GEN, "CKM_DSA_PARAMETER_GEN");
addMech(CKM_DH_PKCS_PARAMETER_GEN, "CKM_DH_PKCS_PARAMETER_GEN");
addMech(CKM_X9_42_DH_PARAMETER_GEN, "CKM_X9_42_DH_PARAMETER_GEN");
addMech(CKM_DSA_PROBABLISTIC_PARAMETER_GEN,
"CKM_DSA_PROBABLISTIC_PARAMETER_GEN");
addMech(CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN,
"CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN");
addMech(CKM_AES_OFB, "CKM_AES_OFB");
addMech(CKM_AES_CFB64, "CKM_AES_CFB64");
addMech(CKM_AES_CFB8, "CKM_AES_CFB8");
addMech(CKM_AES_CFB128, "CKM_AES_CFB128");
addMech(CKM_AES_CFB1, "CKM_AES_CFB1");
addMech(CKM_AES_KEY_WRAP, "CKM_AES_KEY_WRAP");
addMech(CKM_AES_KEY_WRAP_PAD, "CKM_AES_KEY_WRAP_PAD");
addMech(CKM_RSA_PKCS_TPM_1_1, "CKM_RSA_PKCS_TPM_1_1");
addMech(CKM_RSA_PKCS_OAEP_TPM_1_1, "CKM_RSA_PKCS_OAEP_TPM_1_1");
addMech(CKM_VENDOR_DEFINED, "CKM_VENDOR_DEFINED");
addMech(CKM_NSS_TLS_PRF_GENERAL, "CKM_NSS_TLS_PRF_GENERAL");
@ -808,11 +982,13 @@ public class Functions {
addMech(PCKM_SECURERANDOM, "SecureRandom");
addMech(PCKM_KEYSTORE, "KeyStore");
addHashMech(CKM_SHA_1, "SHA-1");
addHashMech(CKM_SHA224, "SHA-224");
addHashMech(CKM_SHA256, "SHA-256");
addHashMech(CKM_SHA384, "SHA-384");
addHashMech(CKM_SHA512, "SHA-512");
addHashMech(CKM_SHA_1, "SHA-1", "SHA", "SHA1");
addHashMech(CKM_SHA224, "SHA-224", "SHA224");
addHashMech(CKM_SHA256, "SHA-256", "SHA256");
addHashMech(CKM_SHA384, "SHA-384", "SHA384");
addHashMech(CKM_SHA512, "SHA-512", "SHA512");
addHashMech(CKM_SHA512_224, "SHA-512/224", "SHA512/224");
addHashMech(CKM_SHA512_256, "SHA-512/256", "SHA512/256");
addKeyType(CKK_RSA, "CKK_RSA");
addKeyType(CKK_DSA, "CKK_DSA");
@ -837,6 +1013,25 @@ public class Functions {
addKeyType(CKK_CDMF, "CKK_CDMF");
addKeyType(CKK_AES, "CKK_AES");
addKeyType(CKK_BLOWFISH, "CKK_BLOWFISH");
addKeyType(CKK_TWOFISH, "CKK_TWOFISH");
addKeyType(CKK_SECURID, "CKK_SECURID");
addKeyType(CKK_HOTP, "CKK_HOTP");
addKeyType(CKK_ACTI, "CKK_ACTI");
addKeyType(CKK_CAMELLIA, "CKK_CAMELLIA");
addKeyType(CKK_ARIA, "CKK_ARIA");
addKeyType(CKK_MD5_HMAC, "CKK_MD5_HMAC");
addKeyType(CKK_SHA_1_HMAC, "CKK_SHA_1_HMAC");
addKeyType(CKK_RIPEMD128_HMAC, "CKK_RIPEMD128_HMAC");
addKeyType(CKK_RIPEMD160_HMAC, "CKK_RIPEMD160_HMAC");
addKeyType(CKK_SHA256_HMAC, "CKK_SHA256_HMAC");
addKeyType(CKK_SHA384_HMAC, "CKK_SHA384_HMAC");
addKeyType(CKK_SHA512_HMAC, "CKK_SHA512_HMAC");
addKeyType(CKK_SHA224_HMAC, "CKK_SHA224_HMAC");
addKeyType(CKK_SEED, "CKK_SEED");
addKeyType(CKK_GOSTR3410, "CKK_GOSTR3410");
addKeyType(CKK_GOSTR3411, "CKK_GOSTR3411");
addKeyType(CKK_GOST28147, "CKK_GOST28147");
addKeyType(CKK_VENDOR_DEFINED, "CKK_VENDOR_DEFINED");
addKeyType(PCKK_ANY, "*");
@ -855,6 +1050,16 @@ public class Functions {
addAttribute(CKA_OWNER, "CKA_OWNER");
addAttribute(CKA_ATTR_TYPES, "CKA_ATTR_TYPES");
addAttribute(CKA_TRUSTED, "CKA_TRUSTED");
addAttribute(CKA_CERTIFICATE_CATEGORY, "CKA_CERTIFICATE_CATEGORY");
addAttribute(CKA_JAVA_MIDP_SECURITY_DOMAIN,
"CKA_JAVA_MIDP_SECURITY_DOMAIN");
addAttribute(CKA_URL, "CKA_URL");
addAttribute(CKA_HASH_OF_SUBJECT_PUBLIC_KEY,
"CKA_HASH_OF_SUBJECT_PUBLIC_KEY");
addAttribute(CKA_HASH_OF_ISSUER_PUBLIC_KEY,
"CKA_HASH_OF_ISSUER_PUBLIC_KEY");
addAttribute(CKA_NAME_HASH_ALGORITHM, "CKA_NAME_HASH_ALGORITHM");
addAttribute(CKA_CHECK_VALUE, "CKA_CHECK_VALUE");
addAttribute(CKA_KEY_TYPE, "CKA_KEY_TYPE");
addAttribute(CKA_SUBJECT, "CKA_SUBJECT");
addAttribute(CKA_ID, "CKA_ID");
@ -879,6 +1084,7 @@ public class Functions {
addAttribute(CKA_EXPONENT_1, "CKA_EXPONENT_1");
addAttribute(CKA_EXPONENT_2, "CKA_EXPONENT_2");
addAttribute(CKA_COEFFICIENT, "CKA_COEFFICIENT");
addAttribute(CKA_PUBLIC_KEY_INFO, "CKA_PUBLIC_KEY_INFO");
addAttribute(CKA_PRIME, "CKA_PRIME");
addAttribute(CKA_SUBPRIME, "CKA_SUBPRIME");
addAttribute(CKA_BASE, "CKA_BASE");
@ -886,19 +1092,69 @@ public class Functions {
addAttribute(CKA_SUB_PRIME_BITS, "CKA_SUB_PRIME_BITS");
addAttribute(CKA_VALUE_BITS, "CKA_VALUE_BITS");
addAttribute(CKA_VALUE_LEN, "CKA_VALUE_LEN");
addAttribute(CKA_EXTRACTABLE, "CKA_EXTRACTABLE");
addAttribute(CKA_LOCAL, "CKA_LOCAL");
addAttribute(CKA_NEVER_EXTRACTABLE, "CKA_NEVER_EXTRACTABLE");
addAttribute(CKA_ALWAYS_SENSITIVE, "CKA_ALWAYS_SENSITIVE");
addAttribute(CKA_KEY_GEN_MECHANISM, "CKA_KEY_GEN_MECHANISM");
addAttribute(CKA_MODIFIABLE, "CKA_MODIFIABLE");
addAttribute(CKA_COPYABLE, "CKA_COPYABLE");
addAttribute(CKA_DESTROYABLE, "CKA_DESTROYABLE");
addAttribute(CKA_EC_PARAMS, "CKA_EC_PARAMS");
addAttribute(CKA_EC_POINT, "CKA_EC_POINT");
addAttribute(CKA_SECONDARY_AUTH, "CKA_SECONDARY_AUTH");
addAttribute(CKA_AUTH_PIN_FLAGS, "CKA_AUTH_PIN_FLAGS");
addAttribute(CKA_ALWAYS_AUTHENTICATE, "CKA_ALWAYS_AUTHENTICATE");
addAttribute(CKA_WRAP_WITH_TRUSTED, "CKA_WRAP_WITH_TRUSTED");
addAttribute(CKA_WRAP_TEMPLATE, "CKA_WRAP_TEMPLATE");
addAttribute(CKA_UNWRAP_TEMPLATE, "CKA_UNWRAP_TEMPLATE");
addAttribute(CKA_DERIVE_TEMPLATE, "CKA_DERIVE_TEMPLATE");
addAttribute(CKA_OTP_FORMAT, "CKA_OTP_FORMAT");
addAttribute(CKA_OTP_LENGTH, "CKA_OTP_LENGTH");
addAttribute(CKA_OTP_TIME_INTERVAL, "CKA_OTP_TIME_INTERVAL");
addAttribute(CKA_OTP_USER_FRIENDLY_MODE,"CKA_OTP_USER_FRIENDLY_MODE");
addAttribute(CKA_OTP_CHALLENGE_REQUIREMENT,
"CKA_OTP_CHALLENGE_REQUIREMENT");
addAttribute(CKA_OTP_TIME_REQUIREMENT, "CKA_OTP_TIME_REQUIREMENT");
addAttribute(CKA_OTP_COUNTER_REQUIREMENT,
"CKA_OTP_COUNTER_REQUIREMENT");
addAttribute(CKA_OTP_PIN_REQUIREMENT, "CKA_OTP_PIN_REQUIREMENT");
addAttribute(CKA_OTP_COUNTER, "CKA_OTP_COUNTER");
addAttribute(CKA_OTP_TIME, "CKA_OTP_TIME");
addAttribute(CKA_OTP_USER_IDENTIFIER, "CKA_OTP_USER_IDENTIFIER");
addAttribute(CKA_OTP_SERVICE_IDENTIFIER,"CKA_OTP_SERVICE_IDENTIFIER");
addAttribute(CKA_OTP_SERVICE_LOGO, "CKA_OTP_SERVICE_LOGO");
addAttribute(CKA_OTP_SERVICE_LOGO_TYPE, "CKA_OTP_SERVICE_LOGO_TYPE");
addAttribute(CKA_GOSTR3410_PARAMS, "CKA_GOSTR3410_PARAMS");
addAttribute(CKA_GOSTR3411_PARAMS, "CKA_GOSTR3411_PARAMS");
addAttribute(CKA_GOST28147_PARAMS, "CKA_GOST28147_PARAMS");
addAttribute(CKA_HW_FEATURE_TYPE, "CKA_HW_FEATURE_TYPE");
addAttribute(CKA_RESET_ON_INIT, "CKA_RESET_ON_INIT");
addAttribute(CKA_HAS_RESET, "CKA_HAS_RESET");
addAttribute(CKA_PIXEL_X, "CKA_PIXEL_X");
addAttribute(CKA_PIXEL_Y, "CKA_PIXEL_Y");
addAttribute(CKA_RESOLUTION, "CKA_RESOLUTION");
addAttribute(CKA_CHAR_ROWS, "CKA_CHAR_ROWS");
addAttribute(CKA_CHAR_COLUMNS, "CKA_CHAR_COLUMNS");
addAttribute(CKA_COLOR, "CKA_COLOR");
addAttribute(CKA_BITS_PER_PIXEL, "CKA_BITS_PER_PIXEL");
addAttribute(CKA_CHAR_SETS, "CKA_CHAR_SETS");
addAttribute(CKA_ENCODING_METHODS, "CKA_ENCODING_METHODS");
addAttribute(CKA_MIME_TYPES, "CKA_MIME_TYPES");
addAttribute(CKA_MECHANISM_TYPE, "CKA_MECHANISM_TYPE");
addAttribute(CKA_REQUIRED_CMS_ATTRIBUTES,
"CKA_REQUIRED_CMS_ATTRIBUTES");
addAttribute(CKA_DEFAULT_CMS_ATTRIBUTES,"CKA_DEFAULT_CMS_ATTRIBUTES");
addAttribute(CKA_SUPPORTED_CMS_ATTRIBUTES,
"CKA_SUPPORTED_CMS_ATTRIBUTES");
addAttribute(CKA_ALLOWED_MECHANISMS, "CKA_ALLOWED_MECHANISMS");
addAttribute(CKA_VENDOR_DEFINED, "CKA_VENDOR_DEFINED");
addAttribute(CKA_NETSCAPE_DB, "CKA_NETSCAPE_DB");
@ -920,6 +1176,11 @@ public class Functions {
addObjectClass(PCKO_ANY, "*");
addMGF(CKG_MGF1_SHA1, "CKG_MGF1_SHA1");
addMGF(CKG_MGF1_SHA256, "CKG_MGF1_SHA256");
addMGF(CKG_MGF1_SHA384, "CKG_MGF1_SHA384");
addMGF(CKG_MGF1_SHA512, "CKG_MGF1_SHA512");
addMGF(CKG_MGF1_SHA224, "CKG_MGF1_SHA224");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@ -97,6 +97,12 @@ public class PKCS11 {
// static initializer, hence this method is empty.
}
/* *****************************************************************************
* Utility, Resource Clean up
******************************************************************************/
// always return 0L
public static native long freeMechanism(long hMechanism);
/**
* The PKCS#11 module to connect to. This is the PKCS#11 driver of the token;
* e.g. pk2priv.dll.
@ -729,17 +735,25 @@ public class PKCS11 {
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pData the data to get encrypted and the data's length
* @param directIn the address of the to-be-encrypted data
* @param in buffer containing the to-be-encrypted data
* @param inOfs buffer offset of the to-be-encrypted data
* @param inLen length of the to-be-encrypted data
* (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
* @return the encrypted data and the encrypted data's length
* @param directOut the address for the encrypted data
* @param out buffer for the encrypted data
* @param outOfs buffer offset for the encrypted data
* @param outLen buffer size for the encrypted data
* @return the length of encrypted data
* (PKCS#11 param: CK_BYTE_PTR pEncryptedData,
* CK_ULONG_PTR pulEncryptedDataLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pData <> null)
* @postconditions (result <> null)
* @preconditions
* @postconditions
*/
public native int C_Encrypt(long hSession, byte[] in, int inOfs, int inLen,
byte[] out, int outOfs, int outLen) throws PKCS11Exception;
public native int C_Encrypt(long hSession, long directIn, byte[] in,
int inOfs, int inLen, long directOut, byte[] out, int outOfs,
int outLen) throws PKCS11Exception;
/**
@ -749,13 +763,20 @@ public class PKCS11 {
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pPart the data part to get encrypted and the data part's length
* @param directIn the address of the to-be-encrypted data
* @param in buffer containing the to-be-encrypted data
* @param inOfs buffer offset of the to-be-encrypted data
* @param inLen length of the to-be-encrypted data
* (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
* @return the encrypted data part and the encrypted data part's length
* @param directOut the address for the encrypted data
* @param out buffer for the encrypted data
* @param outOfs buffer offset for the encrypted data
* @param outLen buffer size for the encrypted data
* @return the length of encrypted data for this update
* (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
CK_ULONG_PTR pulEncryptedPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pPart <> null)
* @preconditions
* @postconditions
*/
public native int C_EncryptUpdate(long hSession, long directIn, byte[] in,
@ -770,12 +791,16 @@ public class PKCS11 {
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @return the last encrypted data part and the last data part's length
* @param directOut the address for the encrypted data
* @param out buffer for the encrypted data
* @param outOfs buffer offset for the encrypted data
* @param outLen buffer size for the encrypted data
* @return the length of the last part of the encrypted data
* (PKCS#11 param: CK_BYTE_PTR pLastEncryptedPart,
CK_ULONG_PTR pulLastEncryptedPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
* @postconditions
*/
public native int C_EncryptFinal(long hSession, long directOut, byte[] out,
int outOfs, int outLen) throws PKCS11Exception;
@ -805,18 +830,25 @@ public class PKCS11 {
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pEncryptedData the encrypted data to get decrypted and the
* encrypted data's length
* (PKCS#11 param: CK_BYTE_PTR pEncryptedData,
* CK_ULONG ulEncryptedDataLen)
* @return the decrypted data and the data's length
* @param directIn the address of the to-be-decrypted data
* @param in buffer containing the to-be-decrypted data
* @param inOfs buffer offset of the to-be-decrypted data
* @param inLen length of the to-be-decrypted data
* (PKCS#11 param: CK_BYTE_PTR pDecryptedData,
* CK_ULONG ulDecryptedDataLen)
* @param directOut the address for the decrypted data
* @param out buffer for the decrypted data
* @param outOfs buffer offset for the decrypted data
* @param outLen buffer size for the decrypted data
* @return the length of decrypted data
* (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pEncryptedPart <> null)
* @postconditions (result <> null)
* @preconditions
* @postconditions
*/
public native int C_Decrypt(long hSession, byte[] in, int inOfs, int inLen,
byte[] out, int outOfs, int outLen) throws PKCS11Exception;
public native int C_Decrypt(long hSession, long directIn, byte[] in,
int inOfs, int inLen, long directOut, byte[] out, int outOfs,
int outLen) throws PKCS11Exception;
/**
@ -826,14 +858,20 @@ public class PKCS11 {
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pEncryptedPart the encrypted data part to get decrypted and the
* encrypted data part's length
* (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
* CK_ULONG ulEncryptedPartLen)
* @return the decrypted data part and the data part's length
* @param directIn the address of the to-be-decrypted data
* @param in buffer containing the to-be-decrypted data
* @param inOfs buffer offset of the to-be-decrypted data
* @param inLen length of the to-be-decrypted data
* (PKCS#11 param: CK_BYTE_PTR pDecryptedPart,
* CK_ULONG ulDecryptedPartLen)
* @param directOut the address for the decrypted data
* @param out buffer for the decrypted data
* @param outOfs buffer offset for the decrypted data
* @param outLen buffer size for the decrypted data
* @return the length of decrypted data for this update
* (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pEncryptedPart <> null)
* @preconditions
* @postconditions
*/
public native int C_DecryptUpdate(long hSession, long directIn, byte[] in,
@ -848,12 +886,16 @@ public class PKCS11 {
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @return the last decrypted data part and the last data part's length
* @param directOut the address for the decrypted data
* @param out buffer for the decrypted data
* @param outOfs buffer offset for the decrypted data
* @param outLen buffer size for the decrypted data
* @return the length of this last part of decrypted data
* (PKCS#11 param: CK_BYTE_PTR pLastPart,
* CK_ULONG_PTR pulLastPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
* @postconditions
*/
public native int C_DecryptFinal(long hSession, long directOut, byte[] out,
int outOfs, int outLen) throws PKCS11Exception;
@ -1027,6 +1069,7 @@ public class PKCS11 {
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param expectedLen expected signature length, can be 0 if unknown
* @return the signature and the signature's length
* (PKCS#11 param: CK_BYTE_PTR pSignature,
* CK_ULONG_PTR pulSignatureLen)
@ -1285,7 +1328,6 @@ public class PKCS11 {
// byte[] pEncryptedPart) throws PKCS11Exception;
/* *****************************************************************************
* Key management
******************************************************************************/
@ -1692,10 +1734,11 @@ static class SynchronizedPKCS11 extends PKCS11 {
super.C_EncryptInit(hSession, pMechanism, hKey);
}
public synchronized int C_Encrypt(long hSession, byte[] in, int inOfs,
int inLen, byte[] out, int outOfs, int outLen)
public synchronized int C_Encrypt(long hSession, long directIn, byte[] in,
int inOfs, int inLen, long directOut, byte[] out, int outOfs, int outLen)
throws PKCS11Exception {
return super.C_Encrypt(hSession, in, inOfs, inLen, out, outOfs, outLen);
return super.C_Encrypt(hSession, directIn, in, inOfs, inLen,
directOut, out, outOfs, outLen);
}
public synchronized int C_EncryptUpdate(long hSession, long directIn,
@ -1715,10 +1758,11 @@ static class SynchronizedPKCS11 extends PKCS11 {
super.C_DecryptInit(hSession, pMechanism, hKey);
}
public synchronized int C_Decrypt(long hSession, byte[] in, int inOfs,
int inLen, byte[] out, int outOfs, int outLen)
throws PKCS11Exception {
return super.C_Decrypt(hSession, in, inOfs, inLen, out, outOfs, outLen);
public synchronized int C_Decrypt(long hSession, long directIn,
byte[] in, int inOfs, int inLen, long directOut, byte[] out,
int outOfs, int outLen) throws PKCS11Exception {
return super.C_Decrypt(hSession, directIn, in, inOfs, inLen,
directOut, out, outOfs, outLen);
}
public synchronized int C_DecryptUpdate(long hSession, long directIn,

View File

@ -88,6 +88,7 @@ public class PKCS11Exception extends Exception {
0x00000011,
0x00000012,
0x00000013,
0x0000001B,
0x00000020,
0x00000021,
0x00000030,
@ -158,6 +159,13 @@ public class PKCS11Exception extends Exception {
0x00000191,
0x000001A0,
0x000001A1,
0x000001B0,
0x000001B1,
0x000001B5,
0x000001B6,
0x000001B7,
0x000001B8,
0x000001B9,
0x00000200,
0x80000000,
};
@ -176,6 +184,7 @@ public class PKCS11Exception extends Exception {
"CKR_ATTRIBUTE_SENSITIVE",
"CKR_ATTRIBUTE_TYPE_INVALID",
"CKR_ATTRIBUTE_VALUE_INVALID",
"CKR_ACTION_PROHIBITED",
"CKR_DATA_INVALID",
"CKR_DATA_LEN_RANGE",
"CKR_DEVICE_ERROR",
@ -246,6 +255,13 @@ public class PKCS11Exception extends Exception {
"CKR_CRYPTOKI_ALREADY_INITIALIZED",
"CKR_MUTEX_BAD",
"CKR_MUTEX_NOT_LOCKED",
"CKR_NEW_PIN_MODE",
"CKR_NEXT_OTP",
"CKR_EXCEEDED_MAX_ITERATIONS",
"CKR_FIPS_SELF_TEST_FAILED",
"CKR_LIBRARY_LOAD_FAILED",
"CKR_PIN_TOO_WEAK",
"CKR_PUBLIC_KEY_INVALID",
"CKR_FUNCTION_REJECTED",
"CKR_VENDOR_DEFINED",
};

View File

@ -1,20 +1,32 @@
## PKCS #11 Cryptographic Token Interface v2.20 Amendment 3 Header Files
ASIS PKCS #11 Cryptographic Token Interface v2.40
### PKCS #11 Cryptographic Token Interface License
<pre>
### OASIS PKCS #11 Cryptographic Token Interface License
```
License to copy and use this software is granted provided that it is
identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
(Cryptoki)" in all material mentioning or referencing this software.
Copyright (c) OASIS Open 2016. All Rights Reserved.
License is also granted to make and use derivative works provided that
such works are identified as "derived from the RSA Security Inc. PKCS #11
Cryptographic Token Interface (Cryptoki)" in all material mentioning or
referencing the derived work.
All capitalized terms in the following text have the meanings assigned to them in the OASIS
Intellectual Property Rights Policy (the "OASIS IPR Policy"). The full Policy may be found at the
OASIS website: [http://www.oasis-open.org/policies-guidelines/ipr]
RSA Security Inc. makes no representations concerning either the
merchantability of this software or the suitability of this software for
any particular purpose. It is provided "as is" without express or implied
warranty of any kind.
This document and translations of it may be copied and furnished to others, and derivative works
that comment on or otherwise explain it or assist in its implementation may be prepared, copied,
published, and distributed, in whole or in part, without restriction of any kind, provided that
the above copyright notice and this section are included on all such copies and derivative works.
However, this document itself may not be modified in any way, including by removing the copyright
notice or references to OASIS, except as needed for the purpose of developing any document or
deliverable produced by an OASIS Technical Committee (in which case the rules applicable to
copyrights, as set forth in the OASIS IPR Policy, must be followed) or as required to translate it
into languages other than English.
</pre>
The limited permissions granted above are perpetual and will not be revoked by OASIS or its
successors or assigns.
This document and the information contained herein is provided on an "AS IS" basis and OASIS
DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE
USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. OASIS AND ITS MEMBERS WILL NOT BE LIABLE FOR
ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THIS DOCUMENT OR
ANY PART THEREOF.
```

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@ -71,7 +71,7 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1EncryptInit
jobject jMechanism, jlong jKeyHandle)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_OBJECT_HANDLE ckKeyHandle;
CK_RV rv;
@ -80,15 +80,14 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1EncryptInit
ckSessionHandle = jLongToCKULong(jSessionHandle);
ckKeyHandle = jLongToCKULong(jKeyHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return; }
rv = (*ckpFunctions->C_EncryptInit)(ckSessionHandle, &ckMechanism,
rv = (*ckpFunctions->C_EncryptInit)(ckSessionHandle, ckpMechanism,
ckKeyHandle);
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
// if OAEP, then cannot free here
freeCKMechanismPtr(ckpMechanism);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
}
@ -98,54 +97,67 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1EncryptInit
/*
* Class: sun_security_pkcs11_wrapper_PKCS11
* Method: C_Encrypt
* Signature: (J[BII[BII)I
* Signature: (JJ[BIIJ[BII)I
* Parametermapping: *PKCS11*
* @param jlong jSessionHandle CK_SESSION_HANDLE hSession
* @param jlong directIn CK_BYTE_PTR pData
* @param jbyteArray jData CK_BYTE_PTR pData
* CK_ULONG ulDataLen
* @return jbyteArray jEncryptedData CK_BYTE_PTR pEncryptedData
* @param jlong directOut CK_BYTE_PTR pEncryptedData
* @return jint encryptedDataLen CK_BYTE_PTR pEncryptedData
* CK_ULONG_PTR pulEncryptedDataLen
*/
JNIEXPORT jint JNICALL
Java_sun_security_pkcs11_wrapper_PKCS11_C_1Encrypt
(JNIEnv *env, jobject obj, jlong jSessionHandle,
jbyteArray jIn, jint jInOfs, jint jInLen,
jbyteArray jOut, jint jOutOfs, jint jOutLen)
jlong directIn, jbyteArray jIn, jint jInOfs, jint jInLen,
jlong directOut, jbyteArray jOut, jint jOutOfs, jint jOutLen)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_RV rv;
CK_BYTE_PTR inBufP;
CK_BYTE_PTR outBufP;
CK_ULONG ckEncryptedPartLen;
CK_ULONG ckEncryptedLen = 0;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return 0; }
ckSessionHandle = jLongToCKULong(jSessionHandle);
inBufP = (*env)->GetPrimitiveArrayCritical(env, jIn, NULL);
if (inBufP == NULL) { return 0; }
outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
if (outBufP == NULL) {
// Make sure to release inBufP
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
return 0;
if (directIn != 0) {
inBufP = (CK_BYTE_PTR) jlong_to_ptr(directIn);
} else {
inBufP = (*env)->GetPrimitiveArrayCritical(env, jIn, NULL);
if (inBufP == NULL) { return 0; }
}
ckEncryptedPartLen = jOutLen;
if (directOut != 0) {
outBufP = (CK_BYTE_PTR) jlong_to_ptr(directOut);
} else {
outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
if (outBufP == NULL) {
goto cleanup;
}
}
ckEncryptedLen = jOutLen;
rv = (*ckpFunctions->C_Encrypt)(ckSessionHandle,
(CK_BYTE_PTR)(inBufP + jInOfs), jInLen,
(CK_BYTE_PTR)(outBufP + jOutOfs),
&ckEncryptedPartLen);
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
(*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
&ckEncryptedLen);
ckAssertReturnValueOK(env, rv);
return ckEncryptedPartLen;
cleanup:
if (directIn == 0 && inBufP != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
}
if (directOut == 0 && outBufP != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
}
return ckEncryptedLen;
}
#endif
@ -172,7 +184,7 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1EncryptUpdate
CK_BYTE_PTR inBufP;
CK_BYTE_PTR outBufP;
CK_ULONG ckEncryptedPartLen;
CK_ULONG ckEncryptedPartLen = 0;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return 0; }
@ -191,34 +203,26 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1EncryptUpdate
} else {
outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
if (outBufP == NULL) {
// Make sure to release inBufP
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
return 0;
goto cleanup;
}
}
ckEncryptedPartLen = jOutLen;
//printf("EU: inBufP=%i, jInOfs=%i, jInLen=%i, outBufP=%i\n",
// inBufP, jInOfs, jInLen, outBufP);
rv = (*ckpFunctions->C_EncryptUpdate)(ckSessionHandle,
(CK_BYTE_PTR)(inBufP + jInOfs), jInLen,
(CK_BYTE_PTR)(outBufP + jOutOfs),
&ckEncryptedPartLen);
//printf("EU: ckEncryptedPartLen=%i\n", ckEncryptedPartLen);
if (directIn == 0) {
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
}
if (directOut == 0) {
(*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
}
ckAssertReturnValueOK(env, rv);
cleanup:
if (directIn == 0 && inBufP != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
}
if (directOut == 0 && outBufP != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
}
return ckEncryptedPartLen;
}
#endif
@ -257,14 +261,10 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1EncryptFinal
ckLastEncryptedPartLen = jOutLen;
//printf("EF: outBufP=%i\n", outBufP);
rv = (*ckpFunctions->C_EncryptFinal)(ckSessionHandle,
(CK_BYTE_PTR)(outBufP + jOutOfs),
&ckLastEncryptedPartLen);
//printf("EF: ckLastEncryptedPartLen=%i", ckLastEncryptedPartLen);
if (directOut == 0) {
(*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
}
@ -291,7 +291,7 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1DecryptInit
jobject jMechanism, jlong jKeyHandle)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_OBJECT_HANDLE ckKeyHandle;
CK_RV rv;
@ -300,15 +300,14 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1DecryptInit
ckSessionHandle = jLongToCKULong(jSessionHandle);
ckKeyHandle = jLongToCKULong(jKeyHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return; }
rv = (*ckpFunctions->C_DecryptInit)(ckSessionHandle, &ckMechanism,
rv = (*ckpFunctions->C_DecryptInit)(ckSessionHandle, ckpMechanism,
ckKeyHandle);
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
// if OAEP, then cannot free here
freeCKMechanismPtr(ckpMechanism);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
}
@ -318,7 +317,7 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1DecryptInit
/*
* Class: sun_security_pkcs11_wrapper_PKCS11
* Method: C_Decrypt
* Signature: (J[BII[BII)I
* Signature: (JJ[BIIJ[BII)I
* Parametermapping: *PKCS11*
* @param jlong jSessionHandle CK_SESSION_HANDLE hSession
* @param jbyteArray jEncryptedData CK_BYTE_PTR pEncryptedData
@ -329,44 +328,53 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1DecryptInit
JNIEXPORT jint JNICALL
Java_sun_security_pkcs11_wrapper_PKCS11_C_1Decrypt
(JNIEnv *env, jobject obj, jlong jSessionHandle,
jbyteArray jIn, jint jInOfs, jint jInLen,
jbyteArray jOut, jint jOutOfs, jint jOutLen)
jlong directIn, jbyteArray jIn, jint jInOfs, jint jInLen,
jlong directOut, jbyteArray jOut, jint jOutOfs, jint jOutLen)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_RV rv;
CK_BYTE_PTR inBufP;
CK_BYTE_PTR outBufP;
CK_ULONG ckPartLen;
CK_ULONG ckOutLen = 0;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return 0; }
ckSessionHandle = jLongToCKULong(jSessionHandle);
inBufP = (*env)->GetPrimitiveArrayCritical(env, jIn, NULL);
if (inBufP == NULL) { return 0; }
outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
if (outBufP == NULL) {
// Make sure to release inBufP
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
return 0;
if (directIn != 0) {
inBufP = (CK_BYTE_PTR) jlong_to_ptr(directIn);
} else {
inBufP = (*env)->GetPrimitiveArrayCritical(env, jIn, NULL);
if (inBufP == NULL) { return 0; }
}
ckPartLen = jOutLen;
if (directOut != 0) {
outBufP = (CK_BYTE_PTR) jlong_to_ptr(directOut);
} else {
outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
if (outBufP == NULL) {
goto cleanup;
}
}
ckOutLen = jOutLen;
rv = (*ckpFunctions->C_Decrypt)(ckSessionHandle,
(CK_BYTE_PTR)(inBufP + jInOfs), jInLen,
(CK_BYTE_PTR)(outBufP + jOutOfs),
&ckPartLen);
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
(*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
&ckOutLen);
ckAssertReturnValueOK(env, rv);
return ckPartLen;
cleanup:
if (directIn == 0 && inBufP != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
}
if (directOut == 0 && outBufP != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
}
return ckOutLen;
}
#endif
@ -393,7 +401,7 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1DecryptUpdate
CK_BYTE_PTR inBufP;
CK_BYTE_PTR outBufP;
CK_ULONG ckDecryptedPartLen;
CK_ULONG ckDecryptedPartLen = 0;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return 0; }
@ -412,28 +420,24 @@ Java_sun_security_pkcs11_wrapper_PKCS11_C_1DecryptUpdate
} else {
outBufP = (*env)->GetPrimitiveArrayCritical(env, jOut, NULL);
if (outBufP == NULL) {
// Make sure to release inBufP
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
return 0;
goto cleanup;
}
}
ckDecryptedPartLen = jOutLen;
rv = (*ckpFunctions->C_DecryptUpdate)(ckSessionHandle,
(CK_BYTE_PTR)(inBufP + jInOfs), jInLen,
(CK_BYTE_PTR)(outBufP + jOutOfs),
&ckDecryptedPartLen);
if (directIn == 0) {
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
}
if (directOut == 0) {
(*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
}
ckAssertReturnValueOK(env, rv);
cleanup:
if (directIn == 0 && inBufP != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, jIn, inBufP, JNI_ABORT);
}
if (directOut == 0 && outBufP != NULL) {
(*env)->ReleasePrimitiveArrayCritical(env, jOut, outBufP, JNI_COMMIT);
}
return ckDecryptedPartLen;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@ -68,21 +68,19 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DigestInit
(JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_RV rv;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return; }
ckSessionHandle = jLongToCKULong(jSessionHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return; }
rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, &ckMechanism);
rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, ckpMechanism);
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
freeCKMechanismPtr(ckpMechanism);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
}
@ -101,53 +99,50 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DigestInit
* CK_ULONG_PTR pulDigestLen
*/
JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DigestSingle
(JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jbyteArray jIn, jint jInOfs, jint jInLen, jbyteArray jDigest, jint jDigestOfs, jint jDigestLen)
(JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism,
jbyteArray jIn, jint jInOfs, jint jInLen, jbyteArray jDigest,
jint jDigestOfs, jint jDigestLen)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_RV rv;
CK_BYTE_PTR bufP;
CK_BYTE BUF[MAX_STACK_BUFFER_LEN];
CK_BYTE_PTR bufP = BUF;
CK_BYTE DIGESTBUF[MAX_DIGEST_LEN];
CK_ULONG ckDigestLength = min(MAX_DIGEST_LEN, jDigestLen);
CK_MECHANISM ckMechanism;
CK_ULONG ckDigestLength = 0;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return 0; }
ckSessionHandle = jLongToCKULong(jSessionHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return 0; }
rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, &ckMechanism);
rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, ckpMechanism);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { goto cleanup; }
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0; }
if (jInLen <= MAX_STACK_BUFFER_LEN) {
bufP = BUF;
} else {
if (jInLen > MAX_STACK_BUFFER_LEN) {
/* always use single part op, even for large data */
bufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
if (bufP == NULL) {
throwOutOfMemoryError(env, 0);
return 0;
goto cleanup;
}
}
(*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)bufP);
if ((*env)->ExceptionCheck(env)) {
if (bufP != BUF) { free(bufP); }
return 0;
goto cleanup;
}
ckDigestLength = min(MAX_DIGEST_LEN, jDigestLen);
rv = (*ckpFunctions->C_Digest)(ckSessionHandle, bufP, jInLen, DIGESTBUF, &ckDigestLength);
if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
(*env)->SetByteArrayRegion(env, jDigest, jDigestOfs, ckDigestLength, (jbyte *)DIGESTBUF);
}
cleanup:
freeCKMechanismPtr(ckpMechanism);
if (bufP != BUF) { free(bufP); }
return ckDigestLength;
@ -165,7 +160,8 @@ JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DigestSingle
* CK_ULONG ulDataLen
*/
JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DigestUpdate
(JNIEnv *env, jobject obj, jlong jSessionHandle, jlong directIn, jbyteArray jIn, jint jInOfs, jint jInLen)
(JNIEnv *env, jobject obj, jlong jSessionHandle, jlong directIn, jbyteArray jIn,
jint jInOfs, jint jInLen)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_RV rv;
@ -256,7 +252,8 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DigestKey
* CK_ULONG_PTR pulDigestLen
*/
JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DigestFinal
(JNIEnv *env, jobject obj, jlong jSessionHandle, jbyteArray jDigest, jint jDigestOfs, jint jDigestLen)
(JNIEnv *env, jobject obj, jlong jSessionHandle, jbyteArray jDigest,
jint jDigestOfs, jint jDigestLen)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_RV rv;

View File

@ -67,6 +67,7 @@ jobject ckMechanismInfoPtrToJMechanismInfo(JNIEnv *env, const CK_MECHANISM_INFO_
jfieldID pNativeDataID;
jfieldID mech_mechanismID;
jfieldID mech_pParameterID;
jfieldID mech_pHandleID;
jclass jByteArrayClass;
jclass jLongClass;
@ -84,6 +85,23 @@ JNIEXPORT jint JNICALL DEF_JNI_OnLoad(JavaVM *vm, void *reserved) {
/* The native implementation of the methods of the PKCS11Implementation class */
/* ************************************************************************** */
/*
* This method is used to do free the memory allocated for CK_MECHANISM structure.
*
* Class: sun_security_pkcs11_wrapper_PKCS11
* Method: freeMechanism
* Signature: (J)J
*/
JNIEXPORT jlong JNICALL
Java_sun_security_pkcs11_wrapper_PKCS11_freeMechanism
(JNIEnv *env, jclass thisClass, jlong ckpMechanism) {
if (ckpMechanism != 0L) {
freeCKMechanismPtr((CK_MECHANISM_PTR) ckpMechanism);
TRACE1("DEBUG PKCS11_freeMechanism: free pMech = %x\n", (jlong)ckpMechanism);
}
return 0L;
}
/*
* This method is used to do static initialization. This method is static and
* synchronized. Summary: use this method like a static initialization block.
@ -115,11 +133,11 @@ jclass fetchClass(JNIEnv *env, const char *name) {
void prefetchFields(JNIEnv *env, jclass thisClass) {
jclass tmpClass;
/* PKCS11 */
/* PKCS11 - pNativeData */
pNativeDataID = (*env)->GetFieldID(env, thisClass, "pNativeData", "J");
if (pNativeDataID == NULL) { return; }
/* CK_MECHANISM */
/* CK_MECHANISM - mechanism, pParameter, pHandle */
tmpClass = (*env)->FindClass(env, CLASS_MECHANISM);
if (tmpClass == NULL) { return; }
mech_mechanismID = (*env)->GetFieldID(env, tmpClass, "mechanism", "J");
@ -127,6 +145,10 @@ void prefetchFields(JNIEnv *env, jclass thisClass) {
mech_pParameterID = (*env)->GetFieldID(env, tmpClass, "pParameter",
"Ljava/lang/Object;");
if (mech_pParameterID == NULL) { return; }
mech_pHandleID = (*env)->GetFieldID(env, tmpClass, "pHandle", "J");
if (mech_pHandleID == NULL) { return; }
/* java classes for primitive types - byte[], long */
jByteArrayClass = fetchClass(env, "[B");
if (jByteArrayClass == NULL) { return; }
jLongClass = fetchClass(env, "java/lang/Long");

View File

@ -155,7 +155,7 @@ Java_sun_security_pkcs11_wrapper_PKCS11_getNativeKeyInfo
jbyte* nativeKeyInfoArrayRawCkAttributes = NULL;
jbyte* nativeKeyInfoArrayRawCkAttributesPtr = NULL;
jbyte* nativeKeyInfoArrayRawDataPtr = NULL;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
char iv[16] = {0x0};
CK_ULONG ckWrappedKeyLength = 0U;
jbyte* wrappedKeySizeWrappedKeyArrayPtr = NULL;
@ -310,8 +310,8 @@ Java_sun_security_pkcs11_wrapper_PKCS11_getNativeKeyInfo
// Key is sensitive. Need to extract it wrapped.
if (jWrappingKeyHandle != 0) {
jMechanismToCKMechanism(env, jWrappingMech, &ckMechanism);
rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism,
ckpMechanism = jMechanismToCKMechanismPtr(env, jWrappingMech);
rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, ckpMechanism,
jLongToCKULong(jWrappingKeyHandle), ckObjectHandle,
NULL_PTR, &ckWrappedKeyLength);
if (ckWrappedKeyLength != 0) {
@ -339,7 +339,7 @@ Java_sun_security_pkcs11_wrapper_PKCS11_getNativeKeyInfo
wrappedKeyBufferPtr =
(CK_BYTE_PTR) (wrappedKeySizeWrappedKeyArrayPtr +
sizeof(unsigned long));
rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism,
rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, ckpMechanism,
jLongToCKULong(jWrappingKeyHandle),ckObjectHandle,
wrappedKeyBufferPtr, &ckWrappedKeyLength);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
@ -382,6 +382,7 @@ cleanup:
&& returnValue != nativeKeyInfoWrappedKeyArray) {
(*env)->DeleteLocalRef(env, nativeKeyInfoWrappedKeyArray);
}
freeCKMechanismPtr(ckpMechanism);
return returnValue;
}
@ -417,7 +418,7 @@ Java_sun_security_pkcs11_wrapper_PKCS11_createNativeKey
unsigned long totalDataSize = 0UL;
jbyte* wrappedKeySizePtr = NULL;
unsigned int i = 0U;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
char iv[16] = {0x0};
CK_ULONG ckWrappedKeyLength = 0UL;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@ -468,8 +469,8 @@ Java_sun_security_pkcs11_wrapper_PKCS11_createNativeKey
jLongToCKULong(nativeKeyInfoCkAttributesCount), &ckObjectHandle);
} else {
// Wrapped key
jMechanismToCKMechanism(env, jWrappingMech, &ckMechanism);
rv = (*ckpFunctions->C_UnwrapKey)(ckSessionHandle, &ckMechanism,
ckpMechanism = jMechanismToCKMechanismPtr(env, jWrappingMech);
rv = (*ckpFunctions->C_UnwrapKey)(ckSessionHandle, ckpMechanism,
jLongToCKULong(jWrappingKeyHandle),
(CK_BYTE_PTR)(wrappedKeySizePtr + sizeof(unsigned long)),
ckWrappedKeyLength,
@ -490,6 +491,7 @@ cleanup:
nativeKeyInfoArrayRaw, JNI_ABORT);
}
freeCKMechanismPtr(ckpMechanism);
return jObjectHandle;
}
#endif
@ -510,9 +512,9 @@ JNIEXPORT jlong JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1GenerateKey
(JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jobjectArray jTemplate)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
CK_ULONG ckAttributesLength;
CK_ULONG ckAttributesLength = 0;
CK_OBJECT_HANDLE ckKeyHandle = 0;
jlong jKeyHandle = 0L;
CK_RV rv;
@ -521,24 +523,21 @@ JNIEXPORT jlong JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1GenerateKey
if (ckpFunctions == NULL) { return 0L; }
ckSessionHandle = jLongToCKULong(jSessionHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return 0L ; }
jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
if ((*env)->ExceptionCheck(env)) {
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
return 0L;
goto cleanup;
}
rv = (*ckpFunctions->C_GenerateKey)(ckSessionHandle, &ckMechanism, ckpAttributes, ckAttributesLength, &ckKeyHandle);
rv = (*ckpFunctions->C_GenerateKey)(ckSessionHandle, ckpMechanism, ckpAttributes, ckAttributesLength, &ckKeyHandle);
if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
jKeyHandle = ckULongToJLong(ckKeyHandle);
/* cheack, if we must give a initialization vector back to Java */
switch (ckMechanism.mechanism) {
switch (ckpMechanism->mechanism) {
case CKM_PBE_MD2_DES_CBC:
case CKM_PBE_MD5_DES_CBC:
case CKM_PBE_MD5_CAST_CBC:
@ -548,14 +547,12 @@ JNIEXPORT jlong JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1GenerateKey
case CKM_PBE_SHA1_CAST128_CBC:
/* case CKM_PBE_SHA1_CAST5_CBC: the same as CKM_PBE_SHA1_CAST128_CBC */
/* we must copy back the initialization vector to the jMechanism object */
copyBackPBEInitializationVector(env, &ckMechanism, jMechanism);
copyBackPBEInitializationVector(env, ckpMechanism, jMechanism);
break;
}
}
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
cleanup:
freeCKMechanismPtr(ckpMechanism);
freeCKAttributeArray(ckpAttributes, ckAttributesLength);
return jKeyHandle ;
@ -582,14 +579,14 @@ JNIEXPORT jlongArray JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1Generate
jobjectArray jPublicKeyTemplate, jobjectArray jPrivateKeyTemplate)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_ATTRIBUTE_PTR ckpPublicKeyAttributes = NULL_PTR;
CK_ATTRIBUTE_PTR ckpPrivateKeyAttributes = NULL_PTR;
CK_ULONG ckPublicKeyAttributesLength;
CK_ULONG ckPrivateKeyAttributesLength;
CK_ULONG ckPublicKeyAttributesLength = 0;
CK_ULONG ckPrivateKeyAttributesLength = 0;
CK_OBJECT_HANDLE_PTR ckpPublicKeyHandle; /* pointer to Public Key */
CK_OBJECT_HANDLE_PTR ckpPrivateKeyHandle; /* pointer to Private Key */
CK_OBJECT_HANDLE_PTR ckpKeyHandles; /* pointer to array with Public and Private Key */
CK_OBJECT_HANDLE_PTR ckpKeyHandles = NULL; /* pointer to array with Public and Private Key */
jlongArray jKeyHandles = NULL;
CK_RV rv;
int attempts;
@ -599,37 +596,25 @@ JNIEXPORT jlongArray JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1Generate
if (ckpFunctions == NULL) { return NULL; }
ckSessionHandle = jLongToCKULong(jSessionHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return NULL; }
ckpKeyHandles = (CK_OBJECT_HANDLE_PTR) malloc(2 * sizeof(CK_OBJECT_HANDLE));
if (ckpKeyHandles == NULL) {
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
throwOutOfMemoryError(env, 0);
return NULL;
goto cleanup;
}
ckpPublicKeyHandle = ckpKeyHandles; /* first element of array is Public Key */
ckpPrivateKeyHandle = (ckpKeyHandles + 1); /* second element of array is Private Key */
jAttributeArrayToCKAttributeArray(env, jPublicKeyTemplate, &ckpPublicKeyAttributes, &ckPublicKeyAttributesLength);
if ((*env)->ExceptionCheck(env)) {
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
free(ckpKeyHandles);
return NULL;
goto cleanup;
}
jAttributeArrayToCKAttributeArray(env, jPrivateKeyTemplate, &ckpPrivateKeyAttributes, &ckPrivateKeyAttributesLength);
if ((*env)->ExceptionCheck(env)) {
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
free(ckpKeyHandles);
freeCKAttributeArray(ckpPublicKeyAttributes, ckPublicKeyAttributesLength);
return NULL;
goto cleanup;
}
/*
@ -650,7 +635,7 @@ JNIEXPORT jlongArray JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1Generate
* Call C_GenerateKeyPair() several times if CKR_FUNCTION_FAILED occurs.
*/
for (attempts = 0; attempts < MAX_ATTEMPTS; attempts++) {
rv = (*ckpFunctions->C_GenerateKeyPair)(ckSessionHandle, &ckMechanism,
rv = (*ckpFunctions->C_GenerateKeyPair)(ckSessionHandle, ckpMechanism,
ckpPublicKeyAttributes, ckPublicKeyAttributesLength,
ckpPrivateKeyAttributes, ckPrivateKeyAttributesLength,
ckpPublicKeyHandle, ckpPrivateKeyHandle);
@ -666,13 +651,11 @@ JNIEXPORT jlongArray JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1Generate
jKeyHandles = ckULongArrayToJLongArray(env, ckpKeyHandles, 2);
}
if(ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
cleanup:
freeCKMechanismPtr(ckpMechanism);
free(ckpKeyHandles);
freeCKAttributeArray(ckpPublicKeyAttributes, ckPublicKeyAttributesLength);
freeCKAttributeArray(ckpPrivateKeyAttributes, ckPrivateKeyAttributesLength);
return jKeyHandles ;
}
#endif
@ -694,7 +677,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1WrapKey
(JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jWrappingKeyHandle, jlong jKeyHandle)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_OBJECT_HANDLE ckWrappingKeyHandle;
CK_OBJECT_HANDLE ckKeyHandle;
jbyteArray jWrappedKey = NULL;
@ -707,33 +690,30 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1WrapKey
if (ckpFunctions == NULL) { return NULL; }
ckSessionHandle = jLongToCKULong(jSessionHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return NULL; }
ckWrappingKeyHandle = jLongToCKULong(jWrappingKeyHandle);
ckKeyHandle = jLongToCKULong(jKeyHandle);
rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, ckpMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
if (rv == CKR_BUFFER_TOO_SMALL) {
ckpWrappedKey = (CK_BYTE_PTR) malloc(ckWrappedKeyLength);
if (ckpWrappedKey == NULL) {
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
throwOutOfMemoryError(env, 0);
return NULL;
goto cleanup;
}
rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, ckpMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
}
if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
jWrappedKey = ckByteArrayToJByteArray(env, ckpWrappedKey, ckWrappedKeyLength);
}
cleanup:
if (ckpWrappedKey != BUF) { free(ckpWrappedKey); }
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
freeCKMechanismPtr(ckpMechanism);
return jWrappedKey ;
}
#endif
@ -758,12 +738,12 @@ JNIEXPORT jlong JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1UnwrapKey
jbyteArray jWrappedKey, jobjectArray jTemplate)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_OBJECT_HANDLE ckUnwrappingKeyHandle;
CK_BYTE_PTR ckpWrappedKey = NULL_PTR;
CK_ULONG ckWrappedKeyLength;
CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
CK_ULONG ckAttributesLength;
CK_ULONG ckAttributesLength = 0;
CK_OBJECT_HANDLE ckKeyHandle = 0;
jlong jKeyHandle = 0L;
CK_RV rv;
@ -772,29 +752,22 @@ JNIEXPORT jlong JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1UnwrapKey
if (ckpFunctions == NULL) { return 0L; }
ckSessionHandle = jLongToCKULong(jSessionHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return 0L; }
ckUnwrappingKeyHandle = jLongToCKULong(jUnwrappingKeyHandle);
jByteArrayToCKByteArray(env, jWrappedKey, &ckpWrappedKey, &ckWrappedKeyLength);
if ((*env)->ExceptionCheck(env)) {
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
return 0L;
goto cleanup;
}
jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
if ((*env)->ExceptionCheck(env)) {
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
free(ckpWrappedKey);
return 0L;
goto cleanup;
}
rv = (*ckpFunctions->C_UnwrapKey)(ckSessionHandle, &ckMechanism, ckUnwrappingKeyHandle,
rv = (*ckpFunctions->C_UnwrapKey)(ckSessionHandle, ckpMechanism, ckUnwrappingKeyHandle,
ckpWrappedKey, ckWrappedKeyLength,
ckpAttributes, ckAttributesLength, &ckKeyHandle);
@ -803,16 +776,14 @@ JNIEXPORT jlong JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1UnwrapKey
#if 0
/* cheack, if we must give a initialization vector back to Java */
if (ckMechanism.mechanism == CKM_KEY_WRAP_SET_OAEP) {
if (ckpMechanism->mechanism == CKM_KEY_WRAP_SET_OAEP) {
/* we must copy back the unwrapped key info to the jMechanism object */
copyBackSetUnwrappedKey(env, &ckMechanism, jMechanism);
copyBackSetUnwrappedKey(env, ckpMechanism, jMechanism);
}
#endif
}
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
cleanup:
freeCKMechanismPtr(ckpMechanism);
freeCKAttributeArray(ckpAttributes, ckAttributesLength);
free(ckpWrappedKey);
@ -834,26 +805,27 @@ static void freeMasterKeyDeriveParams(CK_SSL3_RANDOM_DATA *RandomInfo, CK_VERSIO
}
}
void ssl3FreeMasterKeyDeriveParams(CK_MECHANISM_PTR ckMechanism) {
CK_SSL3_MASTER_KEY_DERIVE_PARAMS *params = (CK_SSL3_MASTER_KEY_DERIVE_PARAMS *) ckMechanism->pParameter;
void ssl3FreeMasterKeyDeriveParams(CK_MECHANISM_PTR ckpMechanism) {
CK_SSL3_MASTER_KEY_DERIVE_PARAMS *params =
(CK_SSL3_MASTER_KEY_DERIVE_PARAMS *) ckpMechanism->pParameter;
if (params == NULL) {
return;
}
freeMasterKeyDeriveParams(&(params->RandomInfo), params->pVersion);
}
void tls12FreeMasterKeyDeriveParams(CK_MECHANISM_PTR ckMechanism) {
void tls12FreeMasterKeyDeriveParams(CK_MECHANISM_PTR ckpMechanism) {
CK_TLS12_MASTER_KEY_DERIVE_PARAMS *params =
(CK_TLS12_MASTER_KEY_DERIVE_PARAMS *)ckMechanism->pParameter;
(CK_TLS12_MASTER_KEY_DERIVE_PARAMS *)ckpMechanism->pParameter;
if (params == NULL) {
return;
}
freeMasterKeyDeriveParams(&(params->RandomInfo), params->pVersion);
}
void freeEcdh1DeriveParams(CK_MECHANISM_PTR ckMechanism) {
void freeEcdh1DeriveParams(CK_MECHANISM_PTR ckpMechanism) {
CK_ECDH1_DERIVE_PARAMS *params =
(CK_ECDH1_DERIVE_PARAMS *)ckMechanism->pParameter;
(CK_ECDH1_DERIVE_PARAMS *)ckpMechanism->pParameter;
if (params == NULL) {
return;
}
@ -869,7 +841,7 @@ void freeEcdh1DeriveParams(CK_MECHANISM_PTR ckMechanism) {
/*
* Copy back the PRF output to Java.
*/
void copyBackTLSPrfParams(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism)
void copyBackTLSPrfParams(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism, jobject jMechanism)
{
jclass jMechanismClass, jTLSPrfParamsClass;
CK_TLS_PRF_PARAMS *ckTLSPrfParams;
@ -890,13 +862,13 @@ void copyBackTLSPrfParams(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMecha
if (fieldID == NULL) { return; }
jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
ckMechanismType = jLongToCKULong(jMechanismType);
if (ckMechanismType != ckMechanism->mechanism) {
if (ckMechanismType != ckpMechanism->mechanism) {
/* we do not have maching types, this should not occur */
return;
}
/* get the native CK_TLS_PRF_PARAMS */
ckTLSPrfParams = (CK_TLS_PRF_PARAMS *) ckMechanism->pParameter;
ckTLSPrfParams = (CK_TLS_PRF_PARAMS *) ckpMechanism->pParameter;
if (ckTLSPrfParams != NULL_PTR) {
/* get the Java CK_TLS_PRF_PARAMS object (pParameter) */
fieldID = (*env)->GetFieldID(env, jMechanismClass, "pParameter", "Ljava/lang/Object;");
@ -950,10 +922,10 @@ JNIEXPORT jlong JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DeriveKey
(JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jBaseKeyHandle, jobjectArray jTemplate)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_OBJECT_HANDLE ckBaseKeyHandle;
CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
CK_ULONG ckAttributesLength;
CK_ULONG ckAttributesLength = 0;
CK_OBJECT_HANDLE ckKeyHandle = 0;
jlong jKeyHandle = 0L;
CK_RV rv;
@ -963,19 +935,16 @@ JNIEXPORT jlong JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DeriveKey
if (ckpFunctions == NULL) { return 0L; }
ckSessionHandle = jLongToCKULong(jSessionHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return 0L; }
ckBaseKeyHandle = jLongToCKULong(jBaseKeyHandle);
jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
if ((*env)->ExceptionCheck(env)) {
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
}
return 0L;
goto cleanup;
}
switch (ckMechanism.mechanism) {
switch (ckpMechanism->mechanism) {
case CKM_SSL3_KEY_AND_MAC_DERIVE:
case CKM_TLS_KEY_AND_MAC_DERIVE:
case CKM_TLS12_KEY_AND_MAC_DERIVE:
@ -989,60 +958,60 @@ JNIEXPORT jlong JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1DeriveKey
break;
}
rv = (*ckpFunctions->C_DeriveKey)(ckSessionHandle, &ckMechanism, ckBaseKeyHandle,
rv = (*ckpFunctions->C_DeriveKey)(ckSessionHandle, ckpMechanism, ckBaseKeyHandle,
ckpAttributes, ckAttributesLength, phKey);
jKeyHandle = ckLongToJLong(ckKeyHandle);
freeCKAttributeArray(ckpAttributes, ckAttributesLength);
switch (ckMechanism.mechanism) {
switch (ckpMechanism->mechanism) {
case CKM_SSL3_MASTER_KEY_DERIVE:
case CKM_TLS_MASTER_KEY_DERIVE:
/* we must copy back the client version */
ssl3CopyBackClientVersion(env, &ckMechanism, jMechanism);
ssl3FreeMasterKeyDeriveParams(&ckMechanism);
ssl3CopyBackClientVersion(env, ckpMechanism, jMechanism);
ssl3FreeMasterKeyDeriveParams(ckpMechanism);
break;
case CKM_TLS12_MASTER_KEY_DERIVE:
tls12CopyBackClientVersion(env, &ckMechanism, jMechanism);
tls12FreeMasterKeyDeriveParams(&ckMechanism);
tls12CopyBackClientVersion(env, ckpMechanism, jMechanism);
tls12FreeMasterKeyDeriveParams(ckpMechanism);
break;
case CKM_SSL3_MASTER_KEY_DERIVE_DH:
case CKM_TLS_MASTER_KEY_DERIVE_DH:
ssl3FreeMasterKeyDeriveParams(&ckMechanism);
ssl3FreeMasterKeyDeriveParams(ckpMechanism);
break;
case CKM_TLS12_MASTER_KEY_DERIVE_DH:
tls12FreeMasterKeyDeriveParams(&ckMechanism);
tls12FreeMasterKeyDeriveParams(ckpMechanism);
break;
case CKM_SSL3_KEY_AND_MAC_DERIVE:
case CKM_TLS_KEY_AND_MAC_DERIVE:
/* we must copy back the unwrapped key info to the jMechanism object */
ssl3CopyBackKeyMatParams(env, &ckMechanism, jMechanism);
ssl3CopyBackKeyMatParams(env, ckpMechanism, jMechanism);
break;
case CKM_TLS12_KEY_AND_MAC_DERIVE:
/* we must copy back the unwrapped key info to the jMechanism object */
tls12CopyBackKeyMatParams(env, &ckMechanism, jMechanism);
tls12CopyBackKeyMatParams(env, ckpMechanism, jMechanism);
break;
case CKM_TLS_PRF:
copyBackTLSPrfParams(env, &ckMechanism, jMechanism);
copyBackTLSPrfParams(env, ckpMechanism, jMechanism);
break;
case CKM_ECDH1_DERIVE:
freeEcdh1DeriveParams(&ckMechanism);
freeEcdh1DeriveParams(ckpMechanism);
break;
default:
// empty
break;
}
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
jKeyHandle =0L;
}
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
cleanup:
freeCKMechanismPtr(ckpMechanism);
freeCKAttributeArray(ckpAttributes, ckAttributesLength);
return jKeyHandle ;
}
static void copyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism,
static void copyBackClientVersion(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism, jobject jMechanism,
CK_VERSION *ckVersion, const char *class_master_key_derive_params)
{
jclass jMasterKeyDeriveParamsClass, jMechanismClass, jVersionClass;
@ -1059,7 +1028,7 @@ static void copyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism, jobjec
if (fieldID == NULL) { return; }
jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
ckMechanismType = jLongToCKULong(jMechanismType);
if (ckMechanismType != ckMechanism->mechanism) {
if (ckMechanismType != ckpMechanism->mechanism) {
/* we do not have maching types, this should not occur */
return;
}
@ -1102,14 +1071,14 @@ static void copyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism, jobjec
* mechanisms when used for deriving a key.
*
*/
void ssl3CopyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism,
void ssl3CopyBackClientVersion(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism,
jobject jMechanism)
{
CK_SSL3_MASTER_KEY_DERIVE_PARAMS *ckSSL3MasterKeyDeriveParams;
ckSSL3MasterKeyDeriveParams =
(CK_SSL3_MASTER_KEY_DERIVE_PARAMS *)ckMechanism->pParameter;
(CK_SSL3_MASTER_KEY_DERIVE_PARAMS *)ckpMechanism->pParameter;
if (ckSSL3MasterKeyDeriveParams != NULL_PTR) {
copyBackClientVersion(env, ckMechanism, jMechanism,
copyBackClientVersion(env, ckpMechanism, jMechanism,
ckSSL3MasterKeyDeriveParams->pVersion,
CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
}
@ -1121,20 +1090,20 @@ void ssl3CopyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism,
* CKM_TLS12_MASTER_KEY_DERIVE mechanism when used for deriving a key.
*
*/
void tls12CopyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism,
void tls12CopyBackClientVersion(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism,
jobject jMechanism)
{
CK_TLS12_MASTER_KEY_DERIVE_PARAMS *ckTLS12MasterKeyDeriveParams;
ckTLS12MasterKeyDeriveParams =
(CK_TLS12_MASTER_KEY_DERIVE_PARAMS *)ckMechanism->pParameter;
(CK_TLS12_MASTER_KEY_DERIVE_PARAMS *)ckpMechanism->pParameter;
if (ckTLS12MasterKeyDeriveParams != NULL_PTR) {
copyBackClientVersion(env, ckMechanism, jMechanism,
copyBackClientVersion(env, ckpMechanism, jMechanism,
ckTLS12MasterKeyDeriveParams->pVersion,
CLASS_TLS12_MASTER_KEY_DERIVE_PARAMS);
}
}
static void copyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism,
static void copyBackKeyMatParams(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism,
jobject jMechanism, CK_SSL3_RANDOM_DATA *RandomInfo,
CK_SSL3_KEY_MAT_OUT_PTR ckSSL3KeyMatOut, const char *class_key_mat_params)
{
@ -1157,7 +1126,7 @@ static void copyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism,
if (fieldID == NULL) { return; }
jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
ckMechanismType = jLongToCKULong(jMechanismType);
if (ckMechanismType != ckMechanism->mechanism) {
if (ckMechanismType != ckpMechanism->mechanism) {
/* we do not have maching types, this should not occur */
return;
}
@ -1264,13 +1233,13 @@ static void copyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism,
* when used for deriving a key.
*
*/
void ssl3CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism,
void ssl3CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism,
jobject jMechanism)
{
CK_SSL3_KEY_MAT_PARAMS *ckSSL3KeyMatParam;
ckSSL3KeyMatParam = (CK_SSL3_KEY_MAT_PARAMS *)ckMechanism->pParameter;
ckSSL3KeyMatParam = (CK_SSL3_KEY_MAT_PARAMS *)ckpMechanism->pParameter;
if (ckSSL3KeyMatParam != NULL_PTR) {
copyBackKeyMatParams(env, ckMechanism, jMechanism,
copyBackKeyMatParams(env, ckpMechanism, jMechanism,
&(ckSSL3KeyMatParam->RandomInfo),
ckSSL3KeyMatParam->pReturnedKeyMaterial,
CLASS_SSL3_KEY_MAT_PARAMS);
@ -1283,13 +1252,13 @@ void ssl3CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism,
* CKM_TLS12_KEY_AND_MAC_DERIVE mechanism when used for deriving a key.
*
*/
void tls12CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism,
void tls12CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM_PTR ckpMechanism,
jobject jMechanism)
{
CK_TLS12_KEY_MAT_PARAMS *ckTLS12KeyMatParam;
ckTLS12KeyMatParam = (CK_TLS12_KEY_MAT_PARAMS *) ckMechanism->pParameter;
ckTLS12KeyMatParam = (CK_TLS12_KEY_MAT_PARAMS *)ckpMechanism->pParameter;
if (ckTLS12KeyMatParam != NULL_PTR) {
copyBackKeyMatParams(env, ckMechanism, jMechanism,
copyBackKeyMatParams(env, ckpMechanism, jMechanism,
&(ckTLS12KeyMatParam->RandomInfo),
ckTLS12KeyMatParam->pReturnedKeyMaterial,
CLASS_TLS12_KEY_MAT_PARAMS);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@ -181,7 +181,7 @@ CK_C_INITIALIZE_ARGS_PTR makeCKInitArgsAdapter(JNIEnv *env, jobject jInitArgs)
jReserved = (*env)->GetObjectField(env, jInitArgs, fieldID);
/* we try to convert the reserved parameter also */
jObjectToPrimitiveCKObjectPtrPtr(env, jReserved, &(ckpInitArgs->pReserved), &ckReservedLength);
ckpInitArgs->pReserved = jObjectToPrimitiveCKObjectPtr(env, jReserved, &ckReservedLength);
return ckpInitArgs ;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@ -63,31 +63,38 @@
* Parametermapping: *PKCS11*
* @param jlong jSessionHandle CK_SESSION_HANDLE hSession
* @param jobject jMechanism CK_MECHANISM_PTR pMechanism
* @return jlong jKeyHandle CK_OBJECT_HANDLE hKey
* @param jlong jKeyHandle CK_OBJECT_HANDLE hKey
*/
JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1SignInit
(JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jKeyHandle)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_OBJECT_HANDLE ckKeyHandle;
CK_RV rv;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return; }
TRACE0("DEBUG: C_SignInit\n");
ckSessionHandle = jLongToCKULong(jSessionHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return; }
ckKeyHandle = jLongToCKULong(jKeyHandle);
rv = (*ckpFunctions->C_SignInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
rv = (*ckpFunctions->C_SignInit)(ckSessionHandle, ckpMechanism, ckKeyHandle);
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK ||
(ckpMechanism->pParameter == NULL)) {
freeCKMechanismPtr(ckpMechanism);
} else {
(*env)->SetLongField(env, jMechanism, mech_pHandleID, (jlong)ckpMechanism);
TRACE1("DEBUG C_SignInit: stored pMech = 0x%lX\n", (jlong)ckpMechanism);
}
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
TRACE0("FINISHED\n");
}
#endif
@ -95,7 +102,7 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1SignInit
/*
* Class: sun_security_pkcs11_wrapper_PKCS11
* Method: C_Sign
* Signature: (J[B)[B
* Signature: (J[BI)[B
* Parametermapping: *PKCS11*
* @param jlong jSessionHandle CK_SESSION_HANDLE hSession
* @param jbyteArray jData CK_BYTE_PTR pData
@ -108,69 +115,45 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1Sign
{
CK_SESSION_HANDLE ckSessionHandle;
CK_BYTE_PTR ckpData = NULL_PTR;
CK_BYTE_PTR ckpSignature;
CK_ULONG ckDataLength;
CK_ULONG ckSignatureLength = 0;
CK_BYTE_PTR bufP;
CK_ULONG ckSignatureLength;
CK_BYTE BUF[MAX_STACK_BUFFER_LEN];
jbyteArray jSignature = NULL;
CK_RV rv;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return NULL; }
TRACE0("DEBUG: C_Sign\n");
ckSessionHandle = jLongToCKULong(jSessionHandle);
jByteArrayToCKByteArray(env, jData, &ckpData, &ckDataLength);
if ((*env)->ExceptionCheck(env)) { return NULL; }
/* START standard code */
/* first determine the length of the signature */
rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, NULL_PTR, &ckSignatureLength);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
free(ckpData);
if ((*env)->ExceptionCheck(env)) {
return NULL;
}
ckpSignature = (CK_BYTE_PTR) malloc(ckSignatureLength * sizeof(CK_BYTE));
if (ckpSignature == NULL) {
free(ckpData);
throwOutOfMemoryError(env, 0);
return NULL;
}
TRACE1("DEBUG C_Sign: data length = %lu\n", ckDataLength);
/* now get the signature */
rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
/* END standard code */
// unknown signature length
bufP = BUF;
ckSignatureLength = MAX_STACK_BUFFER_LEN;
rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength,
bufP, &ckSignatureLength);
/* START workaround code for operation abort bug in pkcs#11 of Datakey and iButton */
/*
ckpSignature = (CK_BYTE_PTR) malloc(256 * sizeof(CK_BYTE));
if (ckpSignature == NULL) {
free(ckpData);
throwOutOfMemoryError(env, 0);
return NULL;
}
rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
TRACE1("DEBUG C_Sign: ret rv=0x%lX\n", rv);
if (rv == CKR_BUFFER_TOO_SMALL) {
free(ckpSignature);
ckpSignature = (CK_BYTE_PTR) malloc(ckSignatureLength * sizeof(CK_BYTE));
if (ckpSignature == NULL) {
free(ckpData);
throwOutOfMemoryError(env, 0);
return NULL;
}
rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
}
*/
/* END workaround code */
if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
jSignature = ckByteArrayToJByteArray(env, ckpSignature, ckSignatureLength);
jSignature = ckByteArrayToJByteArray(env, bufP, ckSignatureLength);
TRACE1("DEBUG C_Sign: signature length = %lu\n", ckSignatureLength);
}
free(ckpData);
free(ckpSignature);
return jSignature ;
free(ckpData);
if (bufP != BUF) { free(bufP); }
TRACE0("FINISHED\n");
return jSignature;
}
#endif
@ -220,21 +203,20 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1SignUpdate
jsize chunkLen = min(bufLen, jInLen);
(*env)->GetByteArrayRegion(env, jIn, jInOfs, chunkLen, (jbyte *)bufP);
if ((*env)->ExceptionCheck(env)) {
if (bufP != BUF) { free(bufP); }
return;
goto cleanup;
}
rv = (*ckpFunctions->C_SignUpdate)(ckSessionHandle, bufP, chunkLen);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
if (bufP != BUF) {
free(bufP);
}
return;
goto cleanup;
}
jInOfs += chunkLen;
jInLen -= chunkLen;
}
cleanup:
if (bufP != BUF) { free(bufP); }
return;
}
#endif
@ -294,32 +276,37 @@ JNIEXPORT jbyteArray JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1SignFina
* Parametermapping: *PKCS11*
* @param jlong jSessionHandle CK_SESSION_HANDLE hSession
* @param jobject jMechanism CK_MECHANISM_PTR pMechanism
* @return jlong jKeyHandle CK_OBJECT_HANDLE hKey
* @param jlong jKeyHandle CK_OBJECT_HANDLE hKey
*/
JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1SignRecoverInit
(JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jKeyHandle)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_OBJECT_HANDLE ckKeyHandle;
CK_RV rv;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return; }
TRACE0("DEBUG: C_SignRecoverInit\n");
ckSessionHandle = jLongToCKULong(jSessionHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return; }
ckKeyHandle = jLongToCKULong(jKeyHandle);
rv = (*ckpFunctions->C_SignRecoverInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
rv = (*ckpFunctions->C_SignRecoverInit)(ckSessionHandle, ckpMechanism, ckKeyHandle);
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK ||
(ckpMechanism->pParameter == NULL)) {
freeCKMechanismPtr(ckpMechanism);
} else {
(*env)->SetLongField(env, jMechanism, mech_pHandleID, (jlong)ckpMechanism);
TRACE1("DEBUG C_SignRecoverInit, stored pMech = 0x%lX\n", (jlong)ckpMechanism);
}
if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
TRACE0("FINISHED\n");
}
#endif
@ -344,7 +331,7 @@ JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1SignRecover
CK_BYTE OUTBUF[MAX_STACK_BUFFER_LEN];
CK_BYTE_PTR inBufP;
CK_BYTE_PTR outBufP = OUTBUF;
CK_ULONG ckSignatureLength = MAX_STACK_BUFFER_LEN;
CK_ULONG ckSignatureLength = 0;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return 0; }
@ -353,36 +340,35 @@ JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1SignRecover
if (jInLen <= MAX_STACK_BUFFER_LEN) {
inBufP = INBUF;
ckSignatureLength = MAX_STACK_BUFFER_LEN;
} else {
inBufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
if (inBufP == NULL) {
throwOutOfMemoryError(env, 0);
return 0;
}
ckSignatureLength = jInLen;
}
(*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
if ((*env)->ExceptionCheck(env)) {
if (inBufP != INBUF) { free(inBufP); }
return 0;
goto cleanup;
}
rv = (*ckpFunctions->C_SignRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckSignatureLength);
/* re-alloc larger buffer if it fits into our Java buffer */
if ((rv == CKR_BUFFER_TOO_SMALL) && (ckSignatureLength <= jIntToCKULong(jOutLen))) {
outBufP = (CK_BYTE_PTR) malloc(ckSignatureLength);
if (outBufP == NULL) {
if (inBufP != INBUF) {
free(inBufP);
}
throwOutOfMemoryError(env, 0);
return 0;
goto cleanup;
}
rv = (*ckpFunctions->C_SignRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckSignatureLength);
}
if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
(*env)->SetByteArrayRegion(env, jOut, jOutOfs, ckSignatureLength, (jbyte *)outBufP);
}
cleanup:
if (inBufP != INBUF) { free(inBufP); }
if (outBufP != OUTBUF) { free(outBufP); }
@ -398,32 +384,39 @@ JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1SignRecover
* Parametermapping: *PKCS11*
* @param jlong jSessionHandle CK_SESSION_HANDLE hSession
* @param jobject jMechanism CK_MECHANISM_PTR pMechanism
* @return jlong jKeyHandle CK_OBJECT_HANDLE hKey
* @param jlong jKeyHandle CK_OBJECT_HANDLE hKey
*/
JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1VerifyInit
(JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jKeyHandle)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_OBJECT_HANDLE ckKeyHandle;
CK_RV rv;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return; }
TRACE0("DEBUG: C_VerifyInit\n");
ckSessionHandle = jLongToCKULong(jSessionHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
if ((*env)->ExceptionCheck(env)) { return; }
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) {
return;
}
ckKeyHandle = jLongToCKULong(jKeyHandle);
rv = (*ckpFunctions->C_VerifyInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
rv = (*ckpFunctions->C_VerifyInit)(ckSessionHandle, ckpMechanism, ckKeyHandle);
if(ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK ||
(ckpMechanism->pParameter == NULL)) {
freeCKMechanismPtr(ckpMechanism);
} else {
(*env)->SetLongField(env, jMechanism, mech_pHandleID, (jlong)ckpMechanism);
TRACE1("DEBUG C_VerifyInit: stored pMech = 0x%lX\n", (jlong)ckpMechanism);
}
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
TRACE0("FINISHED\n");
}
#endif
@ -447,28 +440,31 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1Verify
CK_BYTE_PTR ckpSignature = NULL_PTR;
CK_ULONG ckDataLength;
CK_ULONG ckSignatureLength;
CK_RV rv;
CK_RV rv = 0;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return; }
ckSessionHandle = jLongToCKULong(jSessionHandle);
jByteArrayToCKByteArray(env, jData, &ckpData, &ckDataLength);
if ((*env)->ExceptionCheck(env)) { return; }
if ((*env)->ExceptionCheck(env)) {
return;
}
jByteArrayToCKByteArray(env, jSignature, &ckpSignature, &ckSignatureLength);
if ((*env)->ExceptionCheck(env)) {
free(ckpData);
return;
goto cleanup;
}
/* verify the signature */
rv = (*ckpFunctions->C_Verify)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, ckSignatureLength);
cleanup:
free(ckpData);
free(ckpSignature);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
ckAssertReturnValueOK(env, rv);
}
#endif
@ -510,7 +506,7 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1VerifyUpdate
bufP = (CK_BYTE_PTR) malloc((size_t)bufLen);
if (bufP == NULL) {
throwOutOfMemoryError(env, 0);
return;
goto cleanup;
}
}
@ -518,19 +514,18 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1VerifyUpdate
jsize chunkLen = min(bufLen, jInLen);
(*env)->GetByteArrayRegion(env, jIn, jInOfs, chunkLen, (jbyte *)bufP);
if ((*env)->ExceptionCheck(env)) {
if (bufP != BUF) { free(bufP); }
return;
goto cleanup;
}
rv = (*ckpFunctions->C_VerifyUpdate)(ckSessionHandle, bufP, chunkLen);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
if (bufP != BUF) { free(bufP); }
return;
goto cleanup;
}
jInOfs += chunkLen;
jInLen -= chunkLen;
}
cleanup:
if (bufP != BUF) { free(bufP); }
}
#endif
@ -558,14 +553,16 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1VerifyFinal
ckSessionHandle = jLongToCKULong(jSessionHandle);
jByteArrayToCKByteArray(env, jSignature, &ckpSignature, &ckSignatureLength);
if ((*env)->ExceptionCheck(env)) { return; }
if ((*env)->ExceptionCheck(env)) {
return;
}
/* verify the signature */
rv = (*ckpFunctions->C_VerifyFinal)(ckSessionHandle, ckpSignature, ckSignatureLength);
free(ckpSignature);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
ckAssertReturnValueOK(env, rv);
}
#endif
@ -583,26 +580,31 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1VerifyRecoverI
(JNIEnv *env, jobject obj, jlong jSessionHandle, jobject jMechanism, jlong jKeyHandle)
{
CK_SESSION_HANDLE ckSessionHandle;
CK_MECHANISM ckMechanism;
CK_MECHANISM_PTR ckpMechanism = NULL;
CK_OBJECT_HANDLE ckKeyHandle;
CK_RV rv;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return; }
TRACE0("DEBUG: C_VerifyRecoverInit\n");
ckSessionHandle = jLongToCKULong(jSessionHandle);
jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
ckpMechanism = jMechanismToCKMechanismPtr(env, jMechanism);
if ((*env)->ExceptionCheck(env)) { return; }
ckKeyHandle = jLongToCKULong(jKeyHandle);
rv = (*ckpFunctions->C_VerifyRecoverInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
rv = (*ckpFunctions->C_VerifyRecoverInit)(ckSessionHandle, ckpMechanism, ckKeyHandle);
if (ckMechanism.pParameter != NULL_PTR) {
free(ckMechanism.pParameter);
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK ||
(ckpMechanism->pParameter == NULL)) {
freeCKMechanismPtr(ckpMechanism);
} else {
(*env)->SetLongField(env, jMechanism, mech_pHandleID, (jlong)ckpMechanism);
TRACE1("DEBUG C_VerifyRecoverInit: stored pMech = 0x%lX\n", (jlong)ckpMechanism);
}
if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
TRACE0("FINISHED\n");
}
#endif
@ -627,7 +629,7 @@ JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1VerifyRecover
CK_BYTE OUTBUF[MAX_STACK_BUFFER_LEN];
CK_BYTE_PTR inBufP;
CK_BYTE_PTR outBufP = OUTBUF;
CK_ULONG ckDataLength = MAX_STACK_BUFFER_LEN;
CK_ULONG ckDataLength = 0;
CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
if (ckpFunctions == NULL) { return 0; }
@ -636,18 +638,19 @@ JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1VerifyRecover
if (jInLen <= MAX_STACK_BUFFER_LEN) {
inBufP = INBUF;
ckDataLength = MAX_STACK_BUFFER_LEN;
} else {
inBufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
if (inBufP == NULL) {
throwOutOfMemoryError(env, 0);
return 0;
}
ckDataLength = jInLen;
}
(*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
if ((*env)->ExceptionCheck(env)) {
if (inBufP != INBUF) { free(inBufP); }
return 0;
goto cleanup;
}
rv = (*ckpFunctions->C_VerifyRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckDataLength);
@ -656,9 +659,8 @@ JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1VerifyRecover
if ((rv == CKR_BUFFER_TOO_SMALL) && (ckDataLength <= jIntToCKULong(jOutLen))) {
outBufP = (CK_BYTE_PTR) malloc(ckDataLength);
if (outBufP == NULL) {
if (inBufP != INBUF) { free(inBufP); }
throwOutOfMemoryError(env, 0);
return 0;
goto cleanup;
}
rv = (*ckpFunctions->C_VerifyRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckDataLength);
}
@ -666,6 +668,7 @@ JNIEXPORT jint JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_C_1VerifyRecover
(*env)->SetByteArrayRegion(env, jOut, jOutOfs, ckDataLength, (jbyte *)outBufP);
}
cleanup:
if (inBufP != INBUF) { free(inBufP); }
if (outBufP != OUTBUF) { free(outBufP); }

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@ -277,16 +277,32 @@ void throwDisconnectedRuntimeException(JNIEnv *env)
* @param attrPtr pointer to the to-be-freed CK_ATTRIBUTE array.
* @param len the length of the array
*/
void freeCKAttributeArray(CK_ATTRIBUTE_PTR attrPtr, int len)
{
int i;
for (i=0; i<len; i++) {
if (attrPtr[i].pValue != NULL_PTR) {
free(attrPtr[i].pValue);
void freeCKAttributeArray(CK_ATTRIBUTE_PTR attrPtr, int len) {
if (attrPtr != NULL) {
int i;
for (i=0; i<len; i++) {
if (attrPtr[i].pValue != NULL_PTR) {
free(attrPtr[i].pValue);
}
}
free(attrPtr);
}
free(attrPtr);
}
/* This function frees the specified CK_MECHANISM_PTR pointer and its
* pParameter. NOTE: mechanism-specific memory allocations have to be
* freed before this call as this method only frees the generic
* memory associated with CK_MECHANISM structure.
*
* @param mechPtr pointer to the to-be-freed CK_MECHANISM structure.
*/
void freeCKMechanismPtr(CK_MECHANISM_PTR mechPtr) {
if (mechPtr != NULL) {
TRACE1("DEBUG: free CK_MECHANISM %x", mechPtr);
free(mechPtr->pParameter);
free(mechPtr);
}
}
/*
@ -964,165 +980,164 @@ CK_CHAR_PTR jCharObjectToCKCharPtr(JNIEnv *env, jobject jObject)
/*
* converts a Java object into a pointer to CK-type or a CK-structure with the length in Bytes.
* The memory of *ckpObjectPtr to be freed after use! This function is only used by
* jAttributeToCKAttribute by now.
* The memory of the returned pointer MUST BE FREED BY CALLER!
*
* @param env - used to call JNI funktions to get the Java classes and objects
* @param jObject - the Java object to convert
* @param ckpObjectPtr - the reference of the new pointer to the new CK-value or CK-structure
* @param ckpLength - the reference of the length in bytes of the new CK-value or CK-structure
* @param ckpLength - pointer to the length (bytes) of the newly-allocated CK-value or CK-structure
* @return ckpObject - pointer to the newly-allocated CK-value or CK-structure
*/
void jObjectToPrimitiveCKObjectPtrPtr(JNIEnv *env, jobject jObject, CK_VOID_PTR *ckpObjectPtr, CK_ULONG *ckpLength)
CK_VOID_PTR jObjectToPrimitiveCKObjectPtr(JNIEnv *env, jobject jObject, CK_ULONG *ckpLength)
{
jclass jLongClass, jBooleanClass, jByteArrayClass, jCharArrayClass;
jclass jByteClass, jDateClass, jCharacterClass, jIntegerClass;
jclass jBooleanArrayClass, jIntArrayClass, jLongArrayClass;
jclass jStringClass;
jclass jObjectClass, jClassClass;
CK_VOID_PTR ckpVoid = *ckpObjectPtr;
CK_VOID_PTR ckpObject;
jmethodID jMethod;
jobject jClassObject;
jstring jClassNameString;
char *classNameString, *exceptionMsgPrefix, *exceptionMsg;
TRACE0("\nDEBUG: jObjectToPrimitiveCKObjectPtrPtr");
TRACE0("\nDEBUG: jObjectToPrimitiveCKObjectPtr");
if (jObject == NULL) {
*ckpObjectPtr = NULL;
*ckpLength = 0;
return;
return NULL;
}
jLongClass = (*env)->FindClass(env, "java/lang/Long");
if (jLongClass == NULL) { return; }
if (jLongClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jLongClass)) {
*ckpObjectPtr = jLongObjectToCKULongPtr(env, jObject);
ckpObject = jLongObjectToCKULongPtr(env, jObject);
*ckpLength = sizeof(CK_ULONG);
TRACE1("<converted long value %X>", *((CK_ULONG *) *ckpObjectPtr));
return;
TRACE1("<converted long value %X>", *((CK_ULONG *) ckpObject));
return ckpObject;
}
jBooleanClass = (*env)->FindClass(env, "java/lang/Boolean");
if (jBooleanClass == NULL) { return; }
if (jBooleanClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jBooleanClass)) {
*ckpObjectPtr = jBooleanObjectToCKBBoolPtr(env, jObject);
ckpObject = jBooleanObjectToCKBBoolPtr(env, jObject);
*ckpLength = sizeof(CK_BBOOL);
TRACE0(" <converted boolean value ");
TRACE0((*((CK_BBOOL *) *ckpObjectPtr) == TRUE) ? "TRUE>" : "FALSE>");
return;
TRACE0((*((CK_BBOOL *) ckpObjectPtr) == TRUE) ? "TRUE>" : "FALSE>");
return ckpObject;
}
jByteArrayClass = (*env)->FindClass(env, "[B");
if (jByteArrayClass == NULL) { return; }
if (jByteArrayClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jByteArrayClass)) {
jByteArrayToCKByteArray(env, jObject, (CK_BYTE_PTR*)ckpObjectPtr, ckpLength);
return;
jByteArrayToCKByteArray(env, jObject, (CK_BYTE_PTR*) &ckpObject, ckpLength);
return ckpObject;
}
jCharArrayClass = (*env)->FindClass(env, "[C");
if (jCharArrayClass == NULL) { return; }
if (jCharArrayClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jCharArrayClass)) {
jCharArrayToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*)ckpObjectPtr, ckpLength);
return;
jCharArrayToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*) &ckpObject, ckpLength);
return ckpObject;
}
jByteClass = (*env)->FindClass(env, "java/lang/Byte");
if (jByteClass == NULL) { return; }
if (jByteClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jByteClass)) {
*ckpObjectPtr = jByteObjectToCKBytePtr(env, jObject);
ckpObject = jByteObjectToCKBytePtr(env, jObject);
*ckpLength = sizeof(CK_BYTE);
TRACE1("<converted byte value %X>", *((CK_BYTE *) *ckpObjectPtr));
return;
TRACE1("<converted byte value %X>", *((CK_BYTE *) ckpObject));
return ckpObject;
}
jDateClass = (*env)->FindClass(env, CLASS_DATE);
if (jDateClass == NULL) { return; }
if (jDateClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jDateClass)) {
*ckpObjectPtr = jDateObjectPtrToCKDatePtr(env, jObject);
ckpObject = jDateObjectPtrToCKDatePtr(env, jObject);
*ckpLength = sizeof(CK_DATE);
TRACE3("<converted date value %.4s-%.2s-%.2s>", (*((CK_DATE *) *ckpObjectPtr)).year, (*((CK_DATE *) *ckpObjectPtr)).month, (*((CK_DATE *) *ckpObjectPtr)).day);
return;
TRACE3("<converted date value %.4s-%.2s-%.2s>", ((CK_DATE *) ckpObject)->year,
((CK_DATE *) ckpObject)->month, ((CK_DATE *) ckpObject)->day);
return ckpObject;
}
jCharacterClass = (*env)->FindClass(env, "java/lang/Character");
if (jCharacterClass == NULL) { return; }
if (jCharacterClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jCharacterClass)) {
*ckpObjectPtr = jCharObjectToCKCharPtr(env, jObject);
ckpObject = jCharObjectToCKCharPtr(env, jObject);
*ckpLength = sizeof(CK_UTF8CHAR);
TRACE1("<converted char value %c>", *((CK_CHAR *) *ckpObjectPtr));
return;
TRACE1("<converted char value %c>", *((CK_CHAR *) ckpObject));
return ckpObject;
}
jIntegerClass = (*env)->FindClass(env, "java/lang/Integer");
if (jIntegerClass == NULL) { return; }
if (jIntegerClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jIntegerClass)) {
*ckpObjectPtr = jIntegerObjectToCKULongPtr(env, jObject);
ckpObject = jIntegerObjectToCKULongPtr(env, jObject);
*ckpLength = sizeof(CK_ULONG);
TRACE1("<converted integer value %X>", *((CK_ULONG *) *ckpObjectPtr));
return;
TRACE1("<converted integer value %X>", *((CK_ULONG *) ckpObject));
return ckpObject;
}
jBooleanArrayClass = (*env)->FindClass(env, "[Z");
if (jBooleanArrayClass == NULL) { return; }
if (jBooleanArrayClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jBooleanArrayClass)) {
jBooleanArrayToCKBBoolArray(env, jObject, (CK_BBOOL**)ckpObjectPtr, ckpLength);
return;
jBooleanArrayToCKBBoolArray(env, jObject, (CK_BBOOL**) &ckpObject, ckpLength);
return ckpObject;
}
jIntArrayClass = (*env)->FindClass(env, "[I");
if (jIntArrayClass == NULL) { return; }
if (jIntArrayClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jIntArrayClass)) {
jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*)ckpObjectPtr, ckpLength);
return;
jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*) &ckpObject, ckpLength);
return ckpObject;
}
jLongArrayClass = (*env)->FindClass(env, "[J");
if (jLongArrayClass == NULL) { return; }
if (jLongArrayClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jLongArrayClass)) {
jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*)ckpObjectPtr, ckpLength);
return;
jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*) &ckpObject, ckpLength);
return ckpObject;
}
jStringClass = (*env)->FindClass(env, "java/lang/String");
if (jStringClass == NULL) { return; }
if (jStringClass == NULL) { return NULL; }
if ((*env)->IsInstanceOf(env, jObject, jStringClass)) {
jStringToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*)ckpObjectPtr, ckpLength);
return;
jStringToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*) &ckpObject, ckpLength);
return ckpObject;
}
/* type of jObject unknown, throw PKCS11RuntimeException */
jObjectClass = (*env)->FindClass(env, "java/lang/Object");
if (jObjectClass == NULL) { return; }
if (jObjectClass == NULL) { return NULL; }
jMethod = (*env)->GetMethodID(env, jObjectClass, "getClass", "()Ljava/lang/Class;");
if (jMethod == NULL) { return; }
if (jMethod == NULL) { return NULL; }
jClassObject = (*env)->CallObjectMethod(env, jObject, jMethod);
assert(jClassObject != 0);
jClassClass = (*env)->FindClass(env, "java/lang/Class");
if (jClassClass == NULL) { return; }
if (jClassClass == NULL) { return NULL; }
jMethod = (*env)->GetMethodID(env, jClassClass, "getName", "()Ljava/lang/String;");
if (jMethod == NULL) { return; }
if (jMethod == NULL) { return NULL; }
jClassNameString = (jstring)
(*env)->CallObjectMethod(env, jClassObject, jMethod);
assert(jClassNameString != 0);
classNameString = (char*)
(*env)->GetStringUTFChars(env, jClassNameString, NULL);
if (classNameString == NULL) { return; }
if (classNameString == NULL) { return NULL; }
exceptionMsgPrefix = "Java object of this class cannot be converted to native PKCS#11 type: ";
exceptionMsg = (char *)
malloc((strlen(exceptionMsgPrefix) + strlen(classNameString) + 1));
if (exceptionMsg == NULL) {
(*env)->ReleaseStringUTFChars(env, jClassNameString, classNameString);
throwOutOfMemoryError(env, 0);
return;
return NULL;
}
strcpy(exceptionMsg, exceptionMsgPrefix);
strcat(exceptionMsg, classNameString);
(*env)->ReleaseStringUTFChars(env, jClassNameString, classNameString);
throwPKCS11RuntimeException(env, exceptionMsg);
free(exceptionMsg);
*ckpObjectPtr = NULL;
*ckpLength = 0;
TRACE0("FINISHED\n");
return NULL;
}
#ifdef P11_MEMORYDEBUG

View File

@ -1,124 +0,0 @@
/* pkcs-11v2-20a3.h include file for the PKCS #11 Version 2.20 Amendment 3
document. */
/* $Revision: 1.4 $ */
/* License to copy and use this software is granted provided that it is
* identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
* (Cryptoki) Version 2.20 Amendment 3" in all material mentioning or
* referencing this software.
* RSA Security Inc. makes no representations concerning either the
* merchantability of this software or the suitability of this software for
* any particular purpose. It is provided "as is" without express or implied
* warranty of any kind.
*/
/* This file is preferably included after inclusion of pkcs11.h */
#ifndef _PKCS_11V2_20A3_H_
#define _PKCS_11V2_20A3_H_ 1
/* Are the definitions of this file already included in pkcs11t.h ? */
#ifndef CKK_CAMELLIA
#ifdef __cplusplus
extern "C" {
#endif
/* Key types */
/* Camellia is new for PKCS #11 v2.20 amendment 3 */
#define CKK_CAMELLIA 0x00000025
/* ARIA is new for PKCS #11 v2.20 amendment 3 */
#define CKK_ARIA 0x00000026
/* Mask-generating functions */
/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */
#define CKG_MGF1_SHA224 0x00000005
/* Mechanism Identifiers */
/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */
#define CKM_SHA224 0x00000255
#define CKM_SHA224_HMAC 0x00000256
#define CKM_SHA224_HMAC_GENERAL 0x00000257
/* SHA-224 key derivation is new for PKCS #11 v2.20 amendment 3 */
#define CKM_SHA224_KEY_DERIVATION 0x00000396
/* SHA-224 RSA mechanisms are new for PKCS #11 v2.20 amendment 3 */
#define CKM_SHA224_RSA_PKCS 0x00000046
#define CKM_SHA224_RSA_PKCS_PSS 0x00000047
/* AES counter mode is new for PKCS #11 v2.20 amendment 3 */
#define CKM_AES_CTR 0x00001086
/* Camellia is new for PKCS #11 v2.20 amendment 3 */
#define CKM_CAMELLIA_KEY_GEN 0x00000550
#define CKM_CAMELLIA_ECB 0x00000551
#define CKM_CAMELLIA_CBC 0x00000552
#define CKM_CAMELLIA_MAC 0x00000553
#define CKM_CAMELLIA_MAC_GENERAL 0x00000554
#define CKM_CAMELLIA_CBC_PAD 0x00000555
#define CKM_CAMELLIA_ECB_ENCRYPT_DATA 0x00000556
#define CKM_CAMELLIA_CBC_ENCRYPT_DATA 0x00000557
#define CKM_CAMELLIA_CTR 0x00000558
/* ARIA is new for PKCS #11 v2.20 amendment 3 */
#define CKM_ARIA_KEY_GEN 0x00000560
#define CKM_ARIA_ECB 0x00000561
#define CKM_ARIA_CBC 0x00000562
#define CKM_ARIA_MAC 0x00000563
#define CKM_ARIA_MAC_GENERAL 0x00000564
#define CKM_ARIA_CBC_PAD 0x00000565
#define CKM_ARIA_ECB_ENCRYPT_DATA 0x00000566
#define CKM_ARIA_CBC_ENCRYPT_DATA 0x00000567
/* Mechanism parameters */
/* CK_AES_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */
typedef struct CK_AES_CTR_PARAMS {
CK_ULONG ulCounterBits;
CK_BYTE cb[16];
} CK_AES_CTR_PARAMS;
typedef CK_AES_CTR_PARAMS CK_PTR CK_AES_CTR_PARAMS_PTR;
/* CK_CAMELLIA_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */
typedef struct CK_CAMELLIA_CTR_PARAMS {
CK_ULONG ulCounterBits;
CK_BYTE cb[16];
} CK_CAMELLIA_CTR_PARAMS;
typedef CK_CAMELLIA_CTR_PARAMS CK_PTR CK_CAMELLIA_CTR_PARAMS_PTR;
/* CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */
typedef struct CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS {
CK_BYTE iv[16];
CK_BYTE_PTR pData;
CK_ULONG length;
} CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS;
typedef CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR;
/* CK_ARIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */
typedef struct CK_ARIA_CBC_ENCRYPT_DATA_PARAMS {
CK_BYTE iv[16];
CK_BYTE_PTR pData;
CK_ULONG length;
} CK_ARIA_CBC_ENCRYPT_DATA_PARAMS;
typedef CK_ARIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR;
#ifdef __cplusplus
}
#endif
#endif
#endif

View File

@ -1,19 +1,12 @@
/* pkcs11.h include file for PKCS #11. */
/* $Revision: 1.4 $ */
/* Copyright (c) OASIS Open 2016. All Rights Reserved./
* /Distributed under the terms of the OASIS IPR Policy,
* [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
* IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
*/
/* License to copy and use this software is granted provided that it is
* identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
* (Cryptoki)" in all material mentioning or referencing this software.
* License is also granted to make and use derivative works provided that
* such works are identified as "derived from the RSA Security Inc. PKCS #11
* Cryptographic Token Interface (Cryptoki)" in all material mentioning or
* referencing the derived work.
* RSA Security Inc. makes no representations concerning either the
* merchantability of this software or the suitability of this software for
* any particular purpose. It is provided "as is" without express or implied
* warranty of any kind.
/* Latest version of the specification:
* http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html
*/
#ifndef _PKCS11_H_
@ -24,14 +17,14 @@ extern "C" {
#endif
/* Before including this file (pkcs11.h) (or pkcs11t.h by
* itself), 6 platform-specific macros must be defined. These
* itself), 5 platform-specific macros must be defined. These
* macros are described below, and typical definitions for them
* are also given. Be advised that these definitions can depend
* on both the platform and the compiler used (and possibly also
* on whether a Cryptoki library is linked statically or
* dynamically).
*
* In addition to defining these 6 macros, the packing convention
* In addition to defining these 5 macros, the packing convention
* for Cryptoki structures should be set. The Cryptoki
* convention on packing is that structures should be 1-byte
* aligned.
@ -81,39 +74,7 @@ extern "C" {
* #define CK_PTR *
*
*
* 2. CK_DEFINE_FUNCTION(returnType, name): A macro which makes
* an exportable Cryptoki library function definition out of a
* return type and a function name. It should be used in the
* following fashion to define the exposed Cryptoki functions in
* a Cryptoki library:
*
* CK_DEFINE_FUNCTION(CK_RV, C_Initialize)(
* CK_VOID_PTR pReserved
* )
* {
* ...
* }
*
* If you're using Microsoft Developer Studio 5.0 to define a
* function in a Win32 Cryptoki .dll, it might be defined by:
*
* #define CK_DEFINE_FUNCTION(returnType, name) \
* returnType __declspec(dllexport) name
*
* If you're using an earlier version of Microsoft Developer
* Studio to define a function in a Win16 Cryptoki .dll, it
* might be defined by:
*
* #define CK_DEFINE_FUNCTION(returnType, name) \
* returnType __export _far _pascal name
*
* In a UNIX environment, it might be defined by:
*
* #define CK_DEFINE_FUNCTION(returnType, name) \
* returnType name
*
*
* 3. CK_DECLARE_FUNCTION(returnType, name): A macro which makes
* 2. CK_DECLARE_FUNCTION(returnType, name): A macro which makes
* an importable Cryptoki library function declaration out of a
* return type and a function name. It should be used in the
* following fashion:
@ -141,7 +102,7 @@ extern "C" {
* returnType name
*
*
* 4. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro
* 3. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro
* which makes a Cryptoki API function pointer declaration or
* function pointer type declaration out of a return type and a
* function name. It should be used in the following fashion:
@ -178,7 +139,7 @@ extern "C" {
* returnType (* name)
*
*
* 5. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes
* 4. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes
* a function pointer type for an application callback out of
* a return type for the callback and a name for the callback.
* It should be used in the following fashion:
@ -210,7 +171,7 @@ extern "C" {
* returnType (* name)
*
*
* 6. NULL_PTR: This macro is the value of a NULL pointer.
* 5. NULL_PTR: This macro is the value of a NULL pointer.
*
* In any ANSI/ISO C environment (and in many others as well),
* this should best be defined by
@ -222,7 +183,8 @@ extern "C" {
/* All the various Cryptoki types and #define'd values are in the
* file pkcs11t.h. */
* file pkcs11t.h.
*/
#include "pkcs11t.h"
#define __PASTE(x,y) x##y
@ -238,7 +200,8 @@ extern "C" {
extern CK_DECLARE_FUNCTION(CK_RV, name)
/* pkcs11f.h has all the information about the Cryptoki
* function prototypes. */
* function prototypes.
*/
#include "pkcs11f.h"
#undef CK_NEED_ARG_LIST
@ -257,7 +220,8 @@ extern "C" {
typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, __PASTE(CK_,name))
/* pkcs11f.h has all the information about the Cryptoki
* function prototypes. */
* function prototypes.
*/
#include "pkcs11f.h"
#undef CK_NEED_ARG_LIST
@ -282,7 +246,8 @@ struct CK_FUNCTION_LIST {
/* Pile all the function pointers into the CK_FUNCTION_LIST. */
/* pkcs11f.h has all the information about the Cryptoki
* function prototypes. */
* function prototypes.
*/
#include "pkcs11f.h"
};
@ -296,4 +261,5 @@ struct CK_FUNCTION_LIST {
}
#endif
#endif
#endif /* _PKCS11_H_ */

View File

@ -1,26 +1,20 @@
/* pkcs11f.h include file for PKCS #11. */
/* $Revision: 1.4 $ */
/* License to copy and use this software is granted provided that it is
* identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
* (Cryptoki)" in all material mentioning or referencing this software.
* License is also granted to make and use derivative works provided that
* such works are identified as "derived from the RSA Security Inc. PKCS #11
* Cryptographic Token Interface (Cryptoki)" in all material mentioning or
* referencing the derived work.
* RSA Security Inc. makes no representations concerning either the
* merchantability of this software or the suitability of this software for
* any particular purpose. It is provided "as is" without express or implied
* warranty of any kind.
/* Copyright (c) OASIS Open 2016. All Rights Reserved./
* /Distributed under the terms of the OASIS IPR Policy,
* [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
* IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
*/
/* This header file contains pretty much everything about all the */
/* Cryptoki function prototypes. Because this information is */
/* used for more than just declaring function prototypes, the */
/* order of the functions appearing herein is important, and */
/* should not be altered. */
/* Latest version of the specification:
* http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html
*/
/* This header file contains pretty much everything about all the
* Cryptoki function prototypes. Because this information is
* used for more than just declaring function prototypes, the
* order of the functions appearing herein is important, and
* should not be altered.
*/
/* General-purpose */
@ -30,13 +24,15 @@ CK_PKCS11_FUNCTION_INFO(C_Initialize)
(
CK_VOID_PTR pInitArgs /* if this is not NULL_PTR, it gets
* cast to CK_C_INITIALIZE_ARGS_PTR
* and dereferenced */
* and dereferenced
*/
);
#endif
/* C_Finalize indicates that an application is done with the
* Cryptoki library. */
* Cryptoki library.
*/
CK_PKCS11_FUNCTION_INFO(C_Finalize)
#ifdef CK_NEED_ARG_LIST
(
@ -59,7 +55,8 @@ CK_PKCS11_FUNCTION_INFO(C_GetFunctionList)
#ifdef CK_NEED_ARG_LIST
(
CK_FUNCTION_LIST_PTR_PTR ppFunctionList /* receives pointer to
* function list */
* function list
*/
);
#endif
@ -71,7 +68,7 @@ CK_PKCS11_FUNCTION_INFO(C_GetFunctionList)
CK_PKCS11_FUNCTION_INFO(C_GetSlotList)
#ifdef CK_NEED_ARG_LIST
(
CK_BBOOL tokenPresent, /* only slots with tokens? */
CK_BBOOL tokenPresent, /* only slots with tokens */
CK_SLOT_ID_PTR pSlotList, /* receives array of slot IDs */
CK_ULONG_PTR pulCount /* receives number of slots */
);
@ -79,7 +76,8 @@ CK_PKCS11_FUNCTION_INFO(C_GetSlotList)
/* C_GetSlotInfo obtains information about a particular slot in
* the system. */
* the system.
*/
CK_PKCS11_FUNCTION_INFO(C_GetSlotInfo)
#ifdef CK_NEED_ARG_LIST
(
@ -90,7 +88,8 @@ CK_PKCS11_FUNCTION_INFO(C_GetSlotInfo)
/* C_GetTokenInfo obtains information about a particular token
* in the system. */
* in the system.
*/
CK_PKCS11_FUNCTION_INFO(C_GetTokenInfo)
#ifdef CK_NEED_ARG_LIST
(
@ -101,7 +100,8 @@ CK_PKCS11_FUNCTION_INFO(C_GetTokenInfo)
/* C_GetMechanismList obtains a list of mechanism types
* supported by a token. */
* supported by a token.
*/
CK_PKCS11_FUNCTION_INFO(C_GetMechanismList)
#ifdef CK_NEED_ARG_LIST
(
@ -113,7 +113,8 @@ CK_PKCS11_FUNCTION_INFO(C_GetMechanismList)
/* C_GetMechanismInfo obtains information about a particular
* mechanism possibly supported by a token. */
* mechanism possibly supported by a token.
*/
CK_PKCS11_FUNCTION_INFO(C_GetMechanismInfo)
#ifdef CK_NEED_ARG_LIST
(
@ -127,7 +128,6 @@ CK_PKCS11_FUNCTION_INFO(C_GetMechanismInfo)
/* C_InitToken initializes a token. */
CK_PKCS11_FUNCTION_INFO(C_InitToken)
#ifdef CK_NEED_ARG_LIST
/* pLabel changed from CK_CHAR_PTR to CK_UTF8CHAR_PTR for v2.10 */
(
CK_SLOT_ID slotID, /* ID of the token's slot */
CK_UTF8CHAR_PTR pPin, /* the SO's initial PIN */
@ -165,7 +165,8 @@ CK_PKCS11_FUNCTION_INFO(C_SetPIN)
/* Session management */
/* C_OpenSession opens a session between an application and a
* token. */
* token.
*/
CK_PKCS11_FUNCTION_INFO(C_OpenSession)
#ifdef CK_NEED_ARG_LIST
(
@ -179,7 +180,8 @@ CK_PKCS11_FUNCTION_INFO(C_OpenSession)
/* C_CloseSession closes a session between an application and a
* token. */
* token.
*/
CK_PKCS11_FUNCTION_INFO(C_CloseSession)
#ifdef CK_NEED_ARG_LIST
(
@ -208,7 +210,8 @@ CK_PKCS11_FUNCTION_INFO(C_GetSessionInfo)
/* C_GetOperationState obtains the state of the cryptographic operation
* in a session. */
* in a session.
*/
CK_PKCS11_FUNCTION_INFO(C_GetOperationState)
#ifdef CK_NEED_ARG_LIST
(
@ -220,7 +223,8 @@ CK_PKCS11_FUNCTION_INFO(C_GetOperationState)
/* C_SetOperationState restores the state of the cryptographic
* operation in a session. */
* operation in a session.
*/
CK_PKCS11_FUNCTION_INFO(C_SetOperationState)
#ifdef CK_NEED_ARG_LIST
(
@ -270,7 +274,8 @@ CK_PKCS11_FUNCTION_INFO(C_CreateObject)
/* C_CopyObject copies an object, creating a new object for the
* copy. */
* copy.
*/
CK_PKCS11_FUNCTION_INFO(C_CopyObject)
#ifdef CK_NEED_ARG_LIST
(
@ -305,7 +310,8 @@ CK_PKCS11_FUNCTION_INFO(C_GetObjectSize)
/* C_GetAttributeValue obtains the value of one or more object
* attributes. */
* attributes.
*/
CK_PKCS11_FUNCTION_INFO(C_GetAttributeValue)
#ifdef CK_NEED_ARG_LIST
(
@ -318,7 +324,8 @@ CK_PKCS11_FUNCTION_INFO(C_GetAttributeValue)
/* C_SetAttributeValue modifies the value of one or more object
* attributes */
* attributes.
*/
CK_PKCS11_FUNCTION_INFO(C_SetAttributeValue)
#ifdef CK_NEED_ARG_LIST
(
@ -331,7 +338,8 @@ CK_PKCS11_FUNCTION_INFO(C_SetAttributeValue)
/* C_FindObjectsInit initializes a search for token and session
* objects that match a template. */
* objects that match a template.
*/
CK_PKCS11_FUNCTION_INFO(C_FindObjectsInit)
#ifdef CK_NEED_ARG_LIST
(
@ -344,7 +352,8 @@ CK_PKCS11_FUNCTION_INFO(C_FindObjectsInit)
/* C_FindObjects continues a search for token and session
* objects that match a template, obtaining additional object
* handles. */
* handles.
*/
CK_PKCS11_FUNCTION_INFO(C_FindObjects)
#ifdef CK_NEED_ARG_LIST
(
@ -357,7 +366,8 @@ CK_PKCS11_FUNCTION_INFO(C_FindObjects)
/* C_FindObjectsFinal finishes a search for token and session
* objects. */
* objects.
*/
CK_PKCS11_FUNCTION_INFO(C_FindObjectsFinal)
#ifdef CK_NEED_ARG_LIST
(
@ -394,7 +404,8 @@ CK_PKCS11_FUNCTION_INFO(C_Encrypt)
/* C_EncryptUpdate continues a multiple-part encryption
* operation. */
* operation.
*/
CK_PKCS11_FUNCTION_INFO(C_EncryptUpdate)
#ifdef CK_NEED_ARG_LIST
(
@ -408,7 +419,8 @@ CK_PKCS11_FUNCTION_INFO(C_EncryptUpdate)
/* C_EncryptFinal finishes a multiple-part encryption
* operation. */
* operation.
*/
CK_PKCS11_FUNCTION_INFO(C_EncryptFinal)
#ifdef CK_NEED_ARG_LIST
(
@ -444,7 +456,8 @@ CK_PKCS11_FUNCTION_INFO(C_Decrypt)
/* C_DecryptUpdate continues a multiple-part decryption
* operation. */
* operation.
*/
CK_PKCS11_FUNCTION_INFO(C_DecryptUpdate)
#ifdef CK_NEED_ARG_LIST
(
@ -458,7 +471,8 @@ CK_PKCS11_FUNCTION_INFO(C_DecryptUpdate)
/* C_DecryptFinal finishes a multiple-part decryption
* operation. */
* operation.
*/
CK_PKCS11_FUNCTION_INFO(C_DecryptFinal)
#ifdef CK_NEED_ARG_LIST
(
@ -496,7 +510,8 @@ CK_PKCS11_FUNCTION_INFO(C_Digest)
/* C_DigestUpdate continues a multiple-part message-digesting
* operation. */
* operation.
*/
CK_PKCS11_FUNCTION_INFO(C_DigestUpdate)
#ifdef CK_NEED_ARG_LIST
(
@ -509,7 +524,8 @@ CK_PKCS11_FUNCTION_INFO(C_DigestUpdate)
/* C_DigestKey continues a multi-part message-digesting
* operation, by digesting the value of a secret key as part of
* the data already digested. */
* the data already digested.
*/
CK_PKCS11_FUNCTION_INFO(C_DigestKey)
#ifdef CK_NEED_ARG_LIST
(
@ -520,7 +536,8 @@ CK_PKCS11_FUNCTION_INFO(C_DigestKey)
/* C_DigestFinal finishes a multiple-part message-digesting
* operation. */
* operation.
*/
CK_PKCS11_FUNCTION_INFO(C_DigestFinal)
#ifdef CK_NEED_ARG_LIST
(
@ -537,7 +554,8 @@ CK_PKCS11_FUNCTION_INFO(C_DigestFinal)
/* C_SignInit initializes a signature (private key encryption)
* operation, where the signature is (will be) an appendix to
* the data, and plaintext cannot be recovered from the
*signature. */
* signature.
*/
CK_PKCS11_FUNCTION_INFO(C_SignInit)
#ifdef CK_NEED_ARG_LIST
(
@ -550,7 +568,8 @@ CK_PKCS11_FUNCTION_INFO(C_SignInit)
/* C_Sign signs (encrypts with private key) data in a single
* part, where the signature is (will be) an appendix to the
* data, and plaintext cannot be recovered from the signature. */
* data, and plaintext cannot be recovered from the signature.
*/
CK_PKCS11_FUNCTION_INFO(C_Sign)
#ifdef CK_NEED_ARG_LIST
(
@ -565,7 +584,8 @@ CK_PKCS11_FUNCTION_INFO(C_Sign)
/* C_SignUpdate continues a multiple-part signature operation,
* where the signature is (will be) an appendix to the data,
* and plaintext cannot be recovered from the signature. */
* and plaintext cannot be recovered from the signature.
*/
CK_PKCS11_FUNCTION_INFO(C_SignUpdate)
#ifdef CK_NEED_ARG_LIST
(
@ -577,7 +597,8 @@ CK_PKCS11_FUNCTION_INFO(C_SignUpdate)
/* C_SignFinal finishes a multiple-part signature operation,
* returning the signature. */
* returning the signature.
*/
CK_PKCS11_FUNCTION_INFO(C_SignFinal)
#ifdef CK_NEED_ARG_LIST
(
@ -589,7 +610,8 @@ CK_PKCS11_FUNCTION_INFO(C_SignFinal)
/* C_SignRecoverInit initializes a signature operation, where
* the data can be recovered from the signature. */
* the data can be recovered from the signature.
*/
CK_PKCS11_FUNCTION_INFO(C_SignRecoverInit)
#ifdef CK_NEED_ARG_LIST
(
@ -601,7 +623,8 @@ CK_PKCS11_FUNCTION_INFO(C_SignRecoverInit)
/* C_SignRecover signs data in a single operation, where the
* data can be recovered from the signature. */
* data can be recovered from the signature.
*/
CK_PKCS11_FUNCTION_INFO(C_SignRecover)
#ifdef CK_NEED_ARG_LIST
(
@ -619,7 +642,8 @@ CK_PKCS11_FUNCTION_INFO(C_SignRecover)
/* C_VerifyInit initializes a verification operation, where the
* signature is an appendix to the data, and plaintext cannot
* cannot be recovered from the signature (e.g. DSA). */
* cannot be recovered from the signature (e.g. DSA).
*/
CK_PKCS11_FUNCTION_INFO(C_VerifyInit)
#ifdef CK_NEED_ARG_LIST
(
@ -632,7 +656,8 @@ CK_PKCS11_FUNCTION_INFO(C_VerifyInit)
/* C_Verify verifies a signature in a single-part operation,
* where the signature is an appendix to the data, and plaintext
* cannot be recovered from the signature. */
* cannot be recovered from the signature.
*/
CK_PKCS11_FUNCTION_INFO(C_Verify)
#ifdef CK_NEED_ARG_LIST
(
@ -647,7 +672,8 @@ CK_PKCS11_FUNCTION_INFO(C_Verify)
/* C_VerifyUpdate continues a multiple-part verification
* operation, where the signature is an appendix to the data,
* and plaintext cannot be recovered from the signature. */
* and plaintext cannot be recovered from the signature.
*/
CK_PKCS11_FUNCTION_INFO(C_VerifyUpdate)
#ifdef CK_NEED_ARG_LIST
(
@ -659,7 +685,8 @@ CK_PKCS11_FUNCTION_INFO(C_VerifyUpdate)
/* C_VerifyFinal finishes a multiple-part verification
* operation, checking the signature. */
* operation, checking the signature.
*/
CK_PKCS11_FUNCTION_INFO(C_VerifyFinal)
#ifdef CK_NEED_ARG_LIST
(
@ -671,7 +698,8 @@ CK_PKCS11_FUNCTION_INFO(C_VerifyFinal)
/* C_VerifyRecoverInit initializes a signature verification
* operation, where the data is recovered from the signature. */
* operation, where the data is recovered from the signature.
*/
CK_PKCS11_FUNCTION_INFO(C_VerifyRecoverInit)
#ifdef CK_NEED_ARG_LIST
(
@ -683,7 +711,8 @@ CK_PKCS11_FUNCTION_INFO(C_VerifyRecoverInit)
/* C_VerifyRecover verifies a signature in a single-part
* operation, where the data is recovered from the signature. */
* operation, where the data is recovered from the signature.
*/
CK_PKCS11_FUNCTION_INFO(C_VerifyRecover)
#ifdef CK_NEED_ARG_LIST
(
@ -700,7 +729,8 @@ CK_PKCS11_FUNCTION_INFO(C_VerifyRecover)
/* Dual-function cryptographic operations */
/* C_DigestEncryptUpdate continues a multiple-part digesting
* and encryption operation. */
* and encryption operation.
*/
CK_PKCS11_FUNCTION_INFO(C_DigestEncryptUpdate)
#ifdef CK_NEED_ARG_LIST
(
@ -714,7 +744,8 @@ CK_PKCS11_FUNCTION_INFO(C_DigestEncryptUpdate)
/* C_DecryptDigestUpdate continues a multiple-part decryption and
* digesting operation. */
* digesting operation.
*/
CK_PKCS11_FUNCTION_INFO(C_DecryptDigestUpdate)
#ifdef CK_NEED_ARG_LIST
(
@ -728,7 +759,8 @@ CK_PKCS11_FUNCTION_INFO(C_DecryptDigestUpdate)
/* C_SignEncryptUpdate continues a multiple-part signing and
* encryption operation. */
* encryption operation.
*/
CK_PKCS11_FUNCTION_INFO(C_SignEncryptUpdate)
#ifdef CK_NEED_ARG_LIST
(
@ -742,7 +774,8 @@ CK_PKCS11_FUNCTION_INFO(C_SignEncryptUpdate)
/* C_DecryptVerifyUpdate continues a multiple-part decryption and
* verify operation. */
* verify operation.
*/
CK_PKCS11_FUNCTION_INFO(C_DecryptVerifyUpdate)
#ifdef CK_NEED_ARG_LIST
(
@ -759,7 +792,8 @@ CK_PKCS11_FUNCTION_INFO(C_DecryptVerifyUpdate)
/* Key management */
/* C_GenerateKey generates a secret key, creating a new key
* object. */
* object.
*/
CK_PKCS11_FUNCTION_INFO(C_GenerateKey)
#ifdef CK_NEED_ARG_LIST
(
@ -773,30 +807,19 @@ CK_PKCS11_FUNCTION_INFO(C_GenerateKey)
/* C_GenerateKeyPair generates a public-key/private-key pair,
* creating new key objects. */
* creating new key objects.
*/
CK_PKCS11_FUNCTION_INFO(C_GenerateKeyPair)
#ifdef CK_NEED_ARG_LIST
(
CK_SESSION_HANDLE hSession, /* session
* handle */
CK_MECHANISM_PTR pMechanism, /* key-gen
* mech. */
CK_ATTRIBUTE_PTR pPublicKeyTemplate, /* template
* for pub.
* key */
CK_ULONG ulPublicKeyAttributeCount, /* # pub.
* attrs. */
CK_ATTRIBUTE_PTR pPrivateKeyTemplate, /* template
* for priv.
* key */
CK_ULONG ulPrivateKeyAttributeCount, /* # priv.
* attrs. */
CK_OBJECT_HANDLE_PTR phPublicKey, /* gets pub.
* key
* handle */
CK_OBJECT_HANDLE_PTR phPrivateKey /* gets
* priv. key
* handle */
CK_SESSION_HANDLE hSession, /* session handle */
CK_MECHANISM_PTR pMechanism, /* key-gen mech. */
CK_ATTRIBUTE_PTR pPublicKeyTemplate, /* template for pub. key */
CK_ULONG ulPublicKeyAttributeCount, /* # pub. attrs. */
CK_ATTRIBUTE_PTR pPrivateKeyTemplate, /* template for priv. key */
CK_ULONG ulPrivateKeyAttributeCount, /* # priv. attrs. */
CK_OBJECT_HANDLE_PTR phPublicKey, /* gets pub. key handle */
CK_OBJECT_HANDLE_PTR phPrivateKey /* gets priv. key handle */
);
#endif
@ -816,7 +839,8 @@ CK_PKCS11_FUNCTION_INFO(C_WrapKey)
/* C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new
* key object. */
* key object.
*/
CK_PKCS11_FUNCTION_INFO(C_UnwrapKey)
#ifdef CK_NEED_ARG_LIST
(
@ -833,7 +857,8 @@ CK_PKCS11_FUNCTION_INFO(C_UnwrapKey)
/* C_DeriveKey derives a key from a base key, creating a new key
* object. */
* object.
*/
CK_PKCS11_FUNCTION_INFO(C_DeriveKey)
#ifdef CK_NEED_ARG_LIST
(
@ -851,7 +876,8 @@ CK_PKCS11_FUNCTION_INFO(C_DeriveKey)
/* Random number generation */
/* C_SeedRandom mixes additional seed material into the token's
* random number generator. */
* random number generator.
*/
CK_PKCS11_FUNCTION_INFO(C_SeedRandom)
#ifdef CK_NEED_ARG_LIST
(
@ -878,7 +904,8 @@ CK_PKCS11_FUNCTION_INFO(C_GenerateRandom)
/* C_GetFunctionStatus is a legacy function; it obtains an
* updated status of a function running in parallel with an
* application. */
* application.
*/
CK_PKCS11_FUNCTION_INFO(C_GetFunctionStatus)
#ifdef CK_NEED_ARG_LIST
(
@ -888,7 +915,8 @@ CK_PKCS11_FUNCTION_INFO(C_GetFunctionStatus)
/* C_CancelFunction is a legacy function; it cancels a function
* running in parallel. */
* running in parallel.
*/
CK_PKCS11_FUNCTION_INFO(C_CancelFunction)
#ifdef CK_NEED_ARG_LIST
(
@ -897,11 +925,9 @@ CK_PKCS11_FUNCTION_INFO(C_CancelFunction)
#endif
/* Functions added in for Cryptoki Version 2.01 or later */
/* C_WaitForSlotEvent waits for a slot event (token insertion,
* removal, etc.) to occur. */
* removal, etc.) to occur.
*/
CK_PKCS11_FUNCTION_INFO(C_WaitForSlotEvent)
#ifdef CK_NEED_ARG_LIST
(
@ -910,3 +936,4 @@ CK_PKCS11_FUNCTION_INFO(C_WaitForSlotEvent)
CK_VOID_PTR pRserved /* reserved. Should be NULL_PTR */
);
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
@ -69,11 +69,12 @@
#define CKA_NETSCAPE_BASE (0x80000000 + 0x4E534350)
#define CKA_NETSCAPE_TRUST_BASE (CKA_NETSCAPE_BASE + 0x2000)
#define CKA_NETSCAPE_TRUST_SERVER_AUTH (CKA_NETSCAPE_TRUST_BASE + 8)
#define CKA_NETSCAPE_TRUST_CLIENT_AUTH (CKA_NETSCAPE_TRUST_BASE + 9)
#define CKA_NETSCAPE_TRUST_CODE_SIGNING (CKA_NETSCAPE_TRUST_BASE + 10)
#define CKA_NETSCAPE_TRUST_EMAIL_PROTECTION (CKA_NETSCAPE_TRUST_BASE + 11)
#define CKA_NETSCAPE_DB 0xD5A0DB00
#define CKM_NSS_TLS_PRF_GENERAL 0x80000373
/*
@ -154,11 +155,11 @@
#define P11_ENABLE_GETNATIVEKEYINFO
#define P11_ENABLE_CREATENATIVEKEY
/* include the platform dependent part of the header */
#include "p11_md.h"
#include "pkcs11.h"
#include "pkcs-11v2-20a3.h"
#include <jni.h>
#include <jni_util.h>
#include <stdarg.h>
@ -206,8 +207,6 @@
#define ckULongToJSize(x) ((jsize) x)
#define unsignedIntToCKULong(x) ((CK_ULONG) x)
//#define P11_DEBUG
#ifdef P11_DEBUG
#define TRACE0(s) { printf(s); fflush(stdout); }
#define TRACE1(s, p1) { printf(s, p1); fflush(stdout); }
@ -228,6 +227,8 @@ void printDebug(const char *format, ...);
#define CK_ASSERT_OK 0L
#define CLASS_P11PSSSIGNATURE "sun/security/pkcs11/P11PSSSignature"
#define CLASS_INFO "sun/security/pkcs11/wrapper/CK_INFO"
#define CLASS_VERSION "sun/security/pkcs11/wrapper/CK_VERSION"
#define CLASS_SLOT_INFO "sun/security/pkcs11/wrapper/CK_SLOT_INFO"
@ -249,15 +250,18 @@ void printDebug(const char *format, ...);
/* mechanism parameter classes */
#define CLASS_AES_CTR_PARAMS "sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS"
#define CLASS_GCM_PARAMS "sun/security/pkcs11/wrapper/CK_GCM_PARAMS"
#define CLASS_CCM_PARAMS "sun/security/pkcs11/wrapper/CK_CCM_PARAMS"
#define CLASS_RSA_PKCS_PSS_PARAMS "sun/security/pkcs11/wrapper/CK_RSA_PKCS_PSS_PARAMS"
#define CLASS_RSA_PKCS_OAEP_PARAMS "sun/security/pkcs11/wrapper/CK_RSA_PKCS_OAEP_PARAMS"
#define CLASS_MAC_GENERAL_PARAMS "sun/security/pkcs11/wrapper/CK_MAC_GENERAL_PARAMS"
#define CLASS_PBE_PARAMS "sun/security/pkcs11/wrapper/CK_PBE_PARAMS"
#define PBE_INIT_VECTOR_SIZE 8
#define CLASS_PKCS5_PBKD2_PARAMS "sun/security/pkcs11/wrapper/CK_PKCS5_PBKD2_PARAMS"
#define CLASS_EXTRACT_PARAMS "sun/security/pkcs11/wrapper/CK_EXTRACT_PARAMS"
#define CLASS_RSA_PKCS_PSS_PARAMS "sun/security/pkcs11/wrapper/CK_RSA_PKCS_PSS_PARAMS"
#define CLASS_ECDH1_DERIVE_PARAMS "sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS"
#define CLASS_ECDH2_DERIVE_PARAMS "sun/security/pkcs11/wrapper/CK_ECDH2_DERIVE_PARAMS"
#define CLASS_X9_42_DH1_DERIVE_PARAMS "sun/security/pkcs11/wrapper/CK_X9_42_DH1_DERIVE_PARAMS"
@ -287,7 +291,7 @@ void printDebug(const char *format, ...);
#define CLASS_TLS12_KEY_MAT_PARAMS "sun/security/pkcs11/wrapper/CK_TLS12_KEY_MAT_PARAMS"
#define CLASS_TLS_PRF_PARAMS "sun/security/pkcs11/wrapper/CK_TLS_PRF_PARAMS"
#define CLASS_TLS_MAC_PARAMS "sun/security/pkcs11/wrapper/CK_TLS_MAC_PARAMS"
#define CLASS_AES_CTR_PARAMS "sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS"
/* function to convert a PKCS#11 return value other than CK_OK into a Java Exception
* or to throw a PKCS11RuntimeException
@ -300,11 +304,12 @@ void throwIOException(JNIEnv *env, const char *message);
void throwPKCS11RuntimeException(JNIEnv *env, const char *message);
void throwDisconnectedRuntimeException(JNIEnv *env);
/* function to free CK_ATTRIBUTE array
/* functions to free CK structures and pointers
*/
void freeCKAttributeArray(CK_ATTRIBUTE_PTR attrPtr, int len);
void freeCKMechanismPtr(CK_MECHANISM_PTR mechPtr);
/* funktions to convert Java arrays to a CK-type array and the array length */
/* functions to convert Java arrays to a CK-type array and the array length */
void jBooleanArrayToCKBBoolArray(JNIEnv *env, const jbooleanArray jArray, CK_BBOOL **ckpArray, CK_ULONG_PTR ckLength);
void jByteArrayToCKByteArray(JNIEnv *env, const jbyteArray jArray, CK_BYTE_PTR *ckpArray, CK_ULONG_PTR ckLength);
@ -316,7 +321,7 @@ void jAttributeArrayToCKAttributeArray(JNIEnv *env, jobjectArray jAArray, CK_ATT
/*void jObjectArrayToCKVoidPtrArray(JNIEnv *env, const jobjectArray jArray, CK_VOID_PTR_PTR ckpArray, CK_ULONG_PTR ckpLength); */
/* funktions to convert a CK-type array and the array length to a Java array */
/* functions to convert a CK-type array and the array length to a Java array */
jbyteArray ckByteArrayToJByteArray(JNIEnv *env, const CK_BYTE_PTR ckpArray, CK_ULONG ckLength);
jlongArray ckULongArrayToJLongArray(JNIEnv *env, const CK_ULONG_PTR ckpArray, CK_ULONG ckLength);
@ -324,7 +329,7 @@ jcharArray ckCharArrayToJCharArray(JNIEnv *env, const CK_CHAR_PTR ckpArray, CK_U
jcharArray ckUTF8CharArrayToJCharArray(JNIEnv *env, const CK_UTF8CHAR_PTR ckpArray, CK_ULONG ckLength);
/* funktions to convert a CK-type structure or a pointer to a CK-value to a Java object */
/* functions to convert a CK-type structure or a pointer to a CK-value to a Java object */
jobject ckBBoolPtrToJBooleanObject(JNIEnv *env, const CK_BBOOL* ckpValue);
jobject ckULongPtrToJLongObject(JNIEnv *env, const CK_ULONG_PTR ckpValue);
@ -334,12 +339,12 @@ jobject ckSessionInfoPtrToJSessionInfo(JNIEnv *env, const CK_SESSION_INFO_PTR ck
jobject ckAttributePtrToJAttribute(JNIEnv *env, const CK_ATTRIBUTE_PTR ckpAttribute);
/* funktion to convert the CK-value used by the CK_ATTRIBUTE structure to a Java object */
/* function to convert the CK-value used by the CK_ATTRIBUTE structure to a Java object */
jobject ckAttributeValueToJObject(JNIEnv *env, const CK_ATTRIBUTE_PTR ckpAttribute);
/* funktions to convert a Java object to a CK-type structure or a pointer to a CK-value */
/* functions to convert a Java object to a CK-type structure or a pointer to a CK-value */
CK_BBOOL* jBooleanObjectToCKBBoolPtr(JNIEnv *env, jobject jObject);
CK_BYTE_PTR jByteObjectToCKBytePtr(JNIEnv *env, jobject jObject);
@ -349,44 +354,35 @@ CK_CHAR_PTR jCharObjectToCKCharPtr(JNIEnv *env, jobject jObject);
CK_VERSION_PTR jVersionToCKVersionPtr(JNIEnv *env, jobject jVersion);
CK_DATE * jDateObjectPtrToCKDatePtr(JNIEnv *env, jobject jDate);
CK_ATTRIBUTE jAttributeToCKAttribute(JNIEnv *env, jobject jAttribute);
/*CK_MECHANISM jMechanismToCKMechanism(JNIEnv *env, jobject jMechanism);*/
void jMechanismToCKMechanism(JNIEnv *env, jobject jMechanism, CK_MECHANISM_PTR ckMechanismPtr);
CK_MECHANISM_PTR jMechanismToCKMechanismPtr(JNIEnv *env, jobject jMechanism);
/* funktions to convert Java objects used by the Mechanism and Attribute class to a CK-type structure */
void jObjectToPrimitiveCKObjectPtrPtr(JNIEnv *env, jobject jObject, CK_VOID_PTR *ckpObjectPtr, CK_ULONG *pLength);
void jMechanismParameterToCKMechanismParameter(JNIEnv *env, jobject jParam, CK_VOID_PTR *ckpParamPtr, CK_ULONG *ckpLength);
/* functions to convert Java objects used by the Mechanism and Attribute class to a CK-type structure */
CK_VOID_PTR jObjectToPrimitiveCKObjectPtr(JNIEnv *env, jobject jObject, CK_ULONG *ckpLength);
CK_VOID_PTR jMechParamToCKMechParamPtr(JNIEnv *env, jobject jParam, CK_MECHANISM_TYPE, CK_ULONG
*ckpLength);
/* functions to convert a specific Java mechanism parameter object to a CK-mechanism parameter structure */
CK_RSA_PKCS_OAEP_PARAMS jRsaPkcsOaepParamToCKRsaPkcsOaepParam(JNIEnv *env, jobject jParam);
CK_KEA_DERIVE_PARAMS jKeaDeriveParamToCKKeaDeriveParam(JNIEnv *env, jobject jParam);
CK_RC2_CBC_PARAMS jRc2CbcParamToCKRc2CbcParam(JNIEnv *env, jobject jParam);
CK_RC2_MAC_GENERAL_PARAMS jRc2MacGeneralParamToCKRc2MacGeneralParam(JNIEnv *env, jobject jParam);
CK_RC5_PARAMS jRc5ParamToCKRc5Param(JNIEnv *env, jobject jParam);
CK_RC5_CBC_PARAMS jRc5CbcParamToCKRc5CbcParam(JNIEnv *env, jobject jParam);
CK_RC5_MAC_GENERAL_PARAMS jRc5MacGeneralParamToCKRc5MacGeneralParam(JNIEnv *env, jobject jParam);
CK_SKIPJACK_PRIVATE_WRAP_PARAMS jSkipjackPrivateWrapParamToCKSkipjackPrivateWrapParam(JNIEnv *env, jobject jParam);
CK_SKIPJACK_RELAYX_PARAMS jSkipjackRelayxParamToCKSkipjackRelayxParam(JNIEnv *env, jobject jParam);
CK_PBE_PARAMS jPbeParamToCKPbeParam(JNIEnv *env, jobject jParam);
void jRsaPkcsOaepParamToCKRsaPkcsOaepParam(JNIEnv *env, jobject jParam, CK_RSA_PKCS_OAEP_PARAMS_PTR ckParamPtr);
void jPbeParamToCKPbeParam(JNIEnv *env, jobject jParam, CK_PBE_PARAMS_PTR ckParamPtr);
void copyBackPBEInitializationVector(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
CK_PKCS5_PBKD2_PARAMS jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(JNIEnv *env, jobject jParam);
CK_KEY_WRAP_SET_OAEP_PARAMS jKeyWrapSetOaepParamToCKKeyWrapSetOaepParam(JNIEnv *env, jobject jParam);
void jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(JNIEnv *env, jobject jParam, CK_PKCS5_PBKD2_PARAMS_PTR ckParamPtr);
void copyBackSetUnwrappedKey(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
CK_SSL3_MASTER_KEY_DERIVE_PARAMS jSsl3MasterKeyDeriveParamToCKSsl3MasterKeyDeriveParam(JNIEnv *env, jobject jParam);
void jSsl3MasterKeyDeriveParamToCKSsl3MasterKeyDeriveParam(JNIEnv *env, jobject jParam, CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR ckParamPtr);
void ssl3CopyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
void tls12CopyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
CK_SSL3_KEY_MAT_PARAMS jSsl3KeyMatParamToCKSsl3KeyMatParam(JNIEnv *env, jobject jParam);
void jSsl3KeyMatParamToCKSsl3KeyMatParam(JNIEnv *env, jobject jParam, CK_SSL3_KEY_MAT_PARAMS_PTR ckParamPtr);
void ssl3CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
void tls12CopyBackKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism);
CK_KEY_DERIVATION_STRING_DATA jKeyDerivationStringDataToCKKeyDerivationStringData(JNIEnv *env, jobject jParam);
CK_RSA_PKCS_PSS_PARAMS jRsaPkcsPssParamToCKRsaPkcsPssParam(JNIEnv *env, jobject jParam);
CK_ECDH1_DERIVE_PARAMS jEcdh1DeriveParamToCKEcdh1DeriveParam(JNIEnv *env, jobject jParam);
CK_ECDH2_DERIVE_PARAMS jEcdh2DeriveParamToCKEcdh2DeriveParam(JNIEnv *env, jobject jParam);
CK_X9_42_DH1_DERIVE_PARAMS jX942Dh1DeriveParamToCKX942Dh1DeriveParam(JNIEnv *env, jobject jParam);
CK_X9_42_DH2_DERIVE_PARAMS jX942Dh2DeriveParamToCKX942Dh2DeriveParam(JNIEnv *env, jobject jParam);
void jRsaPkcsPssParamToCKRsaPkcsPssParam(JNIEnv *env, jobject jParam, CK_RSA_PKCS_PSS_PARAMS_PTR ckParamPtr);
void jEcdh1DeriveParamToCKEcdh1DeriveParam(JNIEnv *env, jobject jParam, CK_ECDH1_DERIVE_PARAMS_PTR ckParamPtr);
void jEcdh2DeriveParamToCKEcdh2DeriveParam(JNIEnv *env, jobject jParam,
CK_ECDH2_DERIVE_PARAMS_PTR ckParamPtr);
void jX942Dh1DeriveParamToCKX942Dh1DeriveParam(JNIEnv *env, jobject jParam, CK_X9_42_DH1_DERIVE_PARAMS_PTR ckParamPtr);
void jX942Dh2DeriveParamToCKX942Dh2DeriveParam(JNIEnv *env, jobject jParam, CK_X9_42_DH2_DERIVE_PARAMS_PTR ckParamPtr);
/* functions to convert the InitArgs object for calling the right Java mutex functions */
@ -450,6 +446,7 @@ void destroyLockObject(JNIEnv *env, jobject jLockObject);
extern jfieldID pNativeDataID;
extern jfieldID mech_mechanismID;
extern jfieldID mech_pParameterID;
extern jfieldID mech_pHandleID;
extern jclass jByteArrayClass;
extern jclass jLongClass;

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8080462
* @library /test/lib ..
* @modules jdk.crypto.cryptoki
* @run main Test4512704
* @summary Verify that AES cipher can generate default IV in encrypt mode
*/
import java.io.PrintStream;
import java.security.*;
import java.security.spec.*;
import java.util.Random;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.Provider;
public class Test4512704 extends PKCS11Test {
public void test(String mode, Provider p) throws Exception {
Cipher c;
String transformation = "AES/" + mode + "/NoPadding";
try {
transformation = "AES/" + mode + "/NoPadding";
c = Cipher.getInstance(transformation, p);
} catch (GeneralSecurityException e) {
System.out.println("Skip testing " + p.getName() +
", no support for " + mode);
return;
}
SecretKey key = new SecretKeySpec(new byte[16], "AES");
AlgorithmParameterSpec aps = null;
Cipher ci = Cipher.getInstance(transformation, p);
try {
ci.init(Cipher.ENCRYPT_MODE, key, aps);
} catch(InvalidAlgorithmParameterException ex) {
throw new Exception("parameter should be generated when null is specified!");
}
System.out.println(transformation + ": Passed");
}
public static void main (String[] args) throws Exception {
main(new Test4512704(), args);
}
@Override
public void main(Provider p) throws Exception {
test("GCM", p);
}
}

View File

@ -0,0 +1,109 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8080462
* @library /test/lib ..
* @modules jdk.crypto.cryptoki
* @run main TestCICOWithGCM
* @summary Test CipherInputStream/OutputStream with AES GCM mode.
* @key randomness
*/
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.math.*;
import java.io.*;
import java.util.*;
public class TestCICOWithGCM extends PKCS11Test {
public static void main(String[] args) throws Exception {
main(new TestCICOWithGCM(), args);
}
@Override
public void main(Provider p) throws Exception {
test("GCM", p);
}
public void test(String mode, Provider p) throws Exception {
Cipher c;
try {
String transformation = "AES/" + mode + "/NoPadding";
c = Cipher.getInstance(transformation, p);
} catch (GeneralSecurityException e) {
System.out.println("Skip testing " + p.getName() +
", no support for " + mode);
return;
}
SecretKey key = new SecretKeySpec(new byte[16], "AES");
//do initialization of the plainText
byte[] plainText = new byte[800];
Random rdm = new Random();
rdm.nextBytes(plainText);
//init ciphers
Cipher encCipher = Cipher.getInstance("AES/GCM/NoPadding", p);
encCipher.init(Cipher.ENCRYPT_MODE, key);
Cipher decCipher = Cipher.getInstance("AES/GCM/NoPadding", p);
decCipher.init(Cipher.DECRYPT_MODE, key, encCipher.getParameters());
//init cipher streams
ByteArrayInputStream baInput = new ByteArrayInputStream(plainText);
CipherInputStream ciInput = new CipherInputStream(baInput, encCipher);
ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
CipherOutputStream ciOutput = new CipherOutputStream(baOutput, decCipher);
//do test
byte[] buffer = new byte[800];
int len = ciInput.read(buffer);
System.out.println("read " + len + " bytes from input buffer");
while (len != -1) {
ciOutput.write(buffer, 0, len);
System.out.println("wite " + len + " bytes to output buffer");
len = ciInput.read(buffer);
if (len != -1) {
System.out.println("read " + len + " bytes from input buffer");
} else {
System.out.println("finished reading");
}
}
ciOutput.flush();
ciInput.close();
ciOutput.close();
byte[] recovered = baOutput.toByteArray();
System.out.println("recovered " + recovered.length + " bytes");
if (!Arrays.equals(plainText, recovered)) {
throw new RuntimeException("diff check failed!");
} else {
System.out.println("diff check passed");
}
}
}

View File

@ -0,0 +1,122 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8080462
* @library /test/lib ..
* @modules jdk.crypto.cryptoki
* @run main TestCICOWithGCMAndAAD
* @summary Test CipherInputStream/OutputStream with AES GCM mode with AAD.
* @key randomness
*/
import java.io.*;
import java.security.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class TestCICOWithGCMAndAAD extends PKCS11Test {
public static void main(String[] args) throws Exception {
main(new TestCICOWithGCMAndAAD(), args);
}
@Override
public void main(Provider p) throws Exception {
test("GCM", p);
// test("CCM", p);
}
public void test(String mode, Provider p) throws Exception {
Cipher c;
try {
String transformation = "AES/" + mode + "/NoPadding";
c = Cipher.getInstance(transformation, p);
} catch (GeneralSecurityException e) {
System.out.println("Skip testing " + p.getName() +
", no support for " + mode);
return;
}
SecretKey key = new SecretKeySpec(new byte[16], "AES");
//Do initialization of the plainText
byte[] plainText = new byte[700];
Random rdm = new Random();
rdm.nextBytes(plainText);
byte[] aad = new byte[128];
rdm.nextBytes(aad);
byte[] aad2 = aad.clone();
aad2[50]++;
Cipher encCipher = Cipher.getInstance("AES/GCM/NoPadding", p);
encCipher.init(Cipher.ENCRYPT_MODE, key);
encCipher.updateAAD(aad);
Cipher decCipher = Cipher.getInstance("AES/GCM/NoPadding", p);
decCipher.init(Cipher.DECRYPT_MODE, key, encCipher.getParameters());
decCipher.updateAAD(aad);
byte[] recovered = test(encCipher, decCipher, plainText);
if (!Arrays.equals(plainText, recovered)) {
throw new Exception("sameAAD: diff check failed!");
} else System.out.println("sameAAD: passed");
encCipher.init(Cipher.ENCRYPT_MODE, key);
encCipher.updateAAD(aad2);
recovered = test(encCipher, decCipher, plainText);
if (recovered != null && recovered.length != 0) {
throw new Exception("diffAAD: no data should be returned!");
} else System.out.println("diffAAD: passed");
}
private static byte[] test(Cipher encCipher, Cipher decCipher, byte[] plainText)
throws Exception {
//init cipher streams
ByteArrayInputStream baInput = new ByteArrayInputStream(plainText);
CipherInputStream ciInput = new CipherInputStream(baInput, encCipher);
ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
CipherOutputStream ciOutput = new CipherOutputStream(baOutput, decCipher);
//do test
byte[] buffer = new byte[200];
int len = ciInput.read(buffer);
System.out.println("read " + len + " bytes from input buffer");
while (len != -1) {
ciOutput.write(buffer, 0, len);
System.out.println("wite " + len + " bytes to output buffer");
len = ciInput.read(buffer);
if (len != -1) {
System.out.println("read " + len + " bytes from input buffer");
} else {
System.out.println("finished reading");
}
}
ciOutput.flush();
ciInput.close();
ciOutput.close();
return baOutput.toByteArray();
}
}

View File

@ -0,0 +1,197 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8080462
* @library /test/lib ..
* @modules jdk.crypto.cryptoki
* @run main TestGCMKeyAndIvCheck
* @summary Ensure that same key+iv can't be repeated used for encryption.
*/
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.math.*;
import java.util.*;
public class TestGCMKeyAndIvCheck extends PKCS11Test {
private static final byte[] AAD = new byte[5];
private static final byte[] PT = new byte[18];
public static void main(String[] args) throws Exception {
main(new TestGCMKeyAndIvCheck(), args);
}
private static void checkISE(Cipher c) throws Exception {
// Subsequent encryptions should fail
try {
c.updateAAD(AAD);
throw new Exception("Should throw ISE for updateAAD()");
} catch (IllegalStateException ise) {
// expected
}
try {
c.update(PT);
throw new Exception("Should throw ISE for update()");
} catch (IllegalStateException ise) {
// expected
}
try {
c.doFinal(PT);
throw new Exception("Should throw ISE for doFinal()");
} catch (IllegalStateException ise) {
// expected
}
}
public void test(String mode, Provider p) throws Exception {
Cipher c;
try {
String transformation = "AES/" + mode + "/NoPadding";
c = Cipher.getInstance(transformation, p);
} catch (GeneralSecurityException e) {
System.out.println("Skip testing " + p.getName() +
", no support for " + mode);
return;
}
SecretKey key = new SecretKeySpec(new byte[16], "AES");
// First try parameter-less init.
c.init(Cipher.ENCRYPT_MODE, key);
c.updateAAD(AAD);
byte[] ctPlusTag = c.doFinal(PT);
// subsequent encryption should fail unless re-init w/ different key+iv
checkISE(c);
// Validate the retrieved parameters against the IV and tag length.
AlgorithmParameters params = c.getParameters();
if (params == null) {
throw new Exception("getParameters() should not return null");
}
byte[] iv = null;
int tagLength = 0; // in bits
if (mode.equalsIgnoreCase("GCM")) {
GCMParameterSpec spec = params.getParameterSpec(GCMParameterSpec.class);
tagLength = spec.getTLen();
iv = spec.getIV();
} else {
throw new RuntimeException("Error: Unsupported mode: " + mode);
}
if (tagLength != (ctPlusTag.length - PT.length)*8) {
throw new Exception("Parameters contains incorrect TLen value");
}
if (!Arrays.equals(iv, c.getIV())) {
throw new Exception("Parameters contains incorrect IV value");
}
// Should be ok to use the same key+iv for decryption
c.init(Cipher.DECRYPT_MODE, key, params);
c.updateAAD(AAD);
byte[] recovered = c.doFinal(ctPlusTag);
if (!Arrays.equals(recovered, PT)) {
throw new Exception("decryption result mismatch");
}
// Now try to encrypt again using the same key+iv; should fail also
try {
c.init(Cipher.ENCRYPT_MODE, key, params);
throw new Exception("Should throw exception when same key+iv is used");
} catch (InvalidAlgorithmParameterException iape) {
// expected
}
// Now try to encrypt again using parameter-less init; should work
c.init(Cipher.ENCRYPT_MODE, key);
c.doFinal(PT);
// make sure a different iv is used
byte[] ivNew = c.getIV();
if (Arrays.equals(iv, ivNew)) {
throw new Exception("IV should be different now");
}
// Now try to encrypt again using a different parameter; should work
AlgorithmParameterSpec spec2 = new GCMParameterSpec(128, new byte[30]);
c.init(Cipher.ENCRYPT_MODE, key, spec2);
c.updateAAD(AAD);
c.doFinal(PT);
// subsequent encryption should fail unless re-init w/ different key+iv
checkISE(c);
// Now try decryption twice in a row; no re-init required and
// same parameters is used.
c.init(Cipher.DECRYPT_MODE, key, params);
c.updateAAD(AAD);
recovered = c.doFinal(ctPlusTag);
c.updateAAD(AAD);
recovered = c.doFinal(ctPlusTag);
if (!Arrays.equals(recovered, PT)) {
throw new Exception("decryption result mismatch");
}
// Now try decryption again and re-init using the same parameters
c.init(Cipher.DECRYPT_MODE, key, params);
c.updateAAD(AAD);
recovered = c.doFinal(ctPlusTag);
// init to decrypt w/o parameters; should fail with IKE as
// javadoc specified
try {
c.init(Cipher.DECRYPT_MODE, key);
throw new Exception("Should throw IKE for dec w/o params");
} catch (InvalidKeyException ike) {
// expected
}
// Lastly, try encryption AND decryption w/ wrong type of parameters,
// e.g. IvParameterSpec
try {
c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
throw new Exception("Should throw IAPE");
} catch (InvalidAlgorithmParameterException iape) {
// expected
}
try {
c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
throw new Exception("Should throw IAPE");
} catch (InvalidAlgorithmParameterException iape) {
// expected
}
System.out.println("Test Passed!");
}
@Override
public void main(Provider p) throws Exception {
test("GCM", p);
}
}

View File

@ -0,0 +1,322 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8080462
* @library /test/lib ..
* @modules jdk.crypto.cryptoki
* @run main TestKATForGCM
* @summary Known Answer Test for AES cipher with GCM mode support in
* PKCS11 provider.
*/
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.math.*;
import java.util.*;
public class TestKATForGCM extends PKCS11Test {
// Utility methods
private static byte[] HexToBytes(String hexVal) {
if (hexVal == null) return new byte[0];
byte[] result = new byte[hexVal.length()/2];
for (int i = 0; i < result.length; i++) {
// 2 characters at a time
String byteVal = hexVal.substring(2*i, 2*i +2);
result[i] = Integer.valueOf(byteVal, 16).byteValue();
}
return result;
}
private static class TestVector {
SecretKey key;
byte[] plainText;
byte[] aad;
byte[] cipherText;
byte[] tag;
GCMParameterSpec spec;
String info;
TestVector(String key, String iv, String pt, String aad,
String ct, String tag) {
this.key = new SecretKeySpec(HexToBytes(key), "AES");
this.plainText = HexToBytes(pt);
this.aad = HexToBytes(aad);
this.cipherText = HexToBytes(ct);
this.tag = HexToBytes(tag);
this.spec = new GCMParameterSpec(this.tag.length * 8, HexToBytes(iv));
this.info = "key=" + key + ", iv=" + iv + ", pt=" + pt +
",aad=" + aad + ", ct=" + ct + ", tag=" + tag;
}
public String toString() {
return info;
}
}
// These test vectors are found off NIST's CAVP page
// http://csrc.nist.gov/groups/STM/cavp/index.html
// inside the link named "GCM Test Vectors", i.e.
// http://csrc.nist.gov/groups/STM/cavp/documents/mac/gcmtestvectors.zip
// CAVS 14.0, set of test vectors w/ count = 0, keysize = 128
private static TestVector[] testValues = {
// 96-bit iv w/ 128/120/112/104/96-bit tags
// no plain text, no aad
new TestVector("11754cd72aec309bf52f7687212e8957",
"3c819d9a9bed087615030b65",
null, null, null,
"250327c674aaf477aef2675748cf6971"),
new TestVector("272f16edb81a7abbea887357a58c1917",
"794ec588176c703d3d2a7a07",
null, null, null,
"b6e6f197168f5049aeda32dafbdaeb"),
new TestVector("81b6844aab6a568c4556a2eb7eae752f",
"ce600f59618315a6829bef4d",
null, null, null,
"89b43e9dbc1b4f597dbbc7655bb5"),
new TestVector("cde2f9a9b1a004165ef9dc981f18651b",
"29512c29566c7322e1e33e8e",
null, null, null,
"2e58ce7dabd107c82759c66a75"),
new TestVector("b01e45cc3088aaba9fa43d81d481823f",
"5a2c4a66468713456a4bd5e1",
null, null, null,
"014280f944f53c681164b2ff"),
// 96-bit iv w/ 128/120/112/104/96-bit tags
// no plain text, 16-byte aad
new TestVector("77be63708971c4e240d1cb79e8d77feb",
"e0e00f19fed7ba0136a797f3",
null,
"7a43ec1d9c0a5a78a0b16533a6213cab",
null,
"209fcc8d3675ed938e9c7166709dd946"),
new TestVector("da0b615656135194ba6d3c851099bc48",
"d39d4b4d3cc927885090e6c3",
null,
"e7e5e6f8dac913036cb2ff29e8625e0e",
null,
"ab967711a5770461724460b07237e2"),
new TestVector("7e0986937a88eef894235aba4a2f43b2",
"92c4a631695907166b422d60",
null,
"85c185f8518f9f2cd597a8f9208fc76b",
null,
"3bb916b728df94fe9d1916736be1"),
new TestVector("c3db570d7f0c21e86b028f11465d1dc9",
"f86970f58ceef89fc7cb679e",
null,
"c095240708c0f57c288d86090ae34ee1",
null,
"e043c52160d652e82c7262fcf4"),
new TestVector("bea48ae4980d27f357611014d4486625",
"32bddb5c3aa998a08556454c",
null,
"8a50b0b8c7654bced884f7f3afda2ead",
null,
"8e0f6d8bf05ffebe6f500eb1"),
// 96-bit iv w/ 128/120/112/104/96-bit tags
// no plain text, 20-byte aad
new TestVector("2fb45e5b8f993a2bfebc4b15b533e0b4",
"5b05755f984d2b90f94b8027",
null,
"e85491b2202caf1d7dce03b97e09331c32473941",
null,
"c75b7832b2a2d9bd827412b6ef5769db"),
new TestVector("9bf406339fcef9675bbcf156aa1a0661",
"8be4a9543d40f542abacac95",
null,
"7167cbf56971793186333a6685bbd58d47d379b3",
null,
"5e7968d7bbd5ba58cfcc750e2ef8f1"),
new TestVector("a2e962fff70fd0f4d63be728b80556fc",
"1fa7103483de43d09bc23db4",
null,
"2a58edf1d53f46e4e7ee5e77ee7aeb60fc360658",
null,
"fa37f2dbbefab1451eae1d0d74ca"),
new TestVector("6bf4fdce82926dcdfc52616ed5f23695",
"cc0f5899a10615567e1193ed",
null,
"3340655592374c1da2f05aac3ee111014986107f",
null,
"8ad3385cce3b5e7c985908192c"),
new TestVector("4df7a13e43c3d7b66b1a72fac5ba398e",
"97179a3a2d417908dcf0fb28",
null,
"cbb7fc0010c255661e23b07dbd804b1e06ae70ac",
null,
"37791edae6c137ea946cfb40"),
// 96-bit iv w/ 128-bit tags, 13/16/32/51-byte plain text, no aad
new TestVector("fe9bb47deb3a61e423c2231841cfd1fb",
"4d328eb776f500a2f7fb47aa",
"f1cc3818e421876bb6b8bbd6c9",
null,
"b88c5c1977b35b517b0aeae967",
"43fd4727fe5cdb4b5b42818dea7ef8c9"),
new TestVector("7fddb57453c241d03efbed3ac44e371c",
"ee283a3fc75575e33efd4887",
"d5de42b461646c255c87bd2962d3b9a2",
null,
"2ccda4a5415cb91e135c2a0f78c9b2fd",
"b36d1df9b9d5e596f83e8b7f52971cb3"),
new TestVector("9971071059abc009e4f2bd69869db338",
"07a9a95ea3821e9c13c63251",
"f54bc3501fed4f6f6dfb5ea80106df0bd836e6826225b75c0222f6e859b35983",
null,
"0556c159f84ef36cb1602b4526b12009c775611bffb64dc0d9ca9297cd2c6a01",
"7870d9117f54811a346970f1de090c41"),
new TestVector("594157ec4693202b030f33798b07176d",
"49b12054082660803a1df3df",
"3feef98a976a1bd634f364ac428bb59cd51fb159ec1789946918dbd50ea6c9d594a3a31a5269b0da6936c29d063a5fa2cc8a1c",
null,
"c1b7a46a335f23d65b8db4008a49796906e225474f4fe7d39e55bf2efd97fd82d4167de082ae30fa01e465a601235d8d68bc69",
"ba92d3661ce8b04687e8788d55417dc2"),
// 96-bit iv w/ 128-bit tags, 16-byte plain text, 16/20/48/90-byte aad
new TestVector("c939cc13397c1d37de6ae0e1cb7c423c",
"b3d8cc017cbb89b39e0f67e2",
"c3b3c41f113a31b73d9a5cd432103069",
"24825602bd12a984e0092d3e448eda5f",
"93fe7d9e9bfd10348a5606e5cafa7354",
"0032a1dc85f1c9786925a2e71d8272dd"),
new TestVector("d4a22488f8dd1d5c6c19a7d6ca17964c",
"f3d5837f22ac1a0425e0d1d5",
"7b43016a16896497fb457be6d2a54122",
"f1c5d424b83f96c6ad8cb28ca0d20e475e023b5a",
"c2bd67eef5e95cac27e3b06e3031d0a8",
"f23eacf9d1cdf8737726c58648826e9c"),
new TestVector("89850dd398e1f1e28443a33d40162664",
"e462c58482fe8264aeeb7231",
"2805cdefb3ef6cc35cd1f169f98da81a",
"d74e99d1bdaa712864eec422ac507bddbe2b0d4633cd3dff29ce5059b49fe868526c59a2a3a604457bc2afea866e7606",
"ba80e244b7fc9025cd031d0f63677e06",
"d84a8c3eac57d1bb0e890a8f461d1065"),
new TestVector("bd7c5c63b7542b56a00ebe71336a1588",
"87721f23ba9c3c8ea5571abc",
"de15ddbb1e202161e8a79af6a55ac6f3",
"a6ec8075a0d3370eb7598918f3b93e48444751624997b899a87fa6a9939f844e008aa8b70e9f4c3b1a19d3286bf543e7127bfecba1ad17a5ec53fccc26faecacc4c75369498eaa7d706aef634d0009279b11e4ba6c993e5e9ed9",
"41eb28c0fee4d762de972361c863bc80",
"9cb567220d0b252eb97bff46e4b00ff8"),
// 8/1024-bit iv w/ 128-bit tag, no plain text, no aad
new TestVector("1672c3537afa82004c6b8a46f6f0d026",
"05",
null, null, null,
"8e2ad721f9455f74d8b53d3141f27e8e"),
new TestVector("d0f1f4defa1e8c08b4b26d576392027c",
"42b4f01eb9f5a1ea5b1eb73b0fb0baed54f387ecaa0393c7d7dffc6af50146ecc021abf7eb9038d4303d91f8d741a11743166c0860208bcc02c6258fd9511a2fa626f96d60b72fcff773af4e88e7a923506e4916ecbd814651e9f445adef4ad6a6b6c7290cc13b956130eef5b837c939fcac0cbbcc9656cd75b13823ee5acdac",
null, null, null,
"7ab49b57ddf5f62c427950111c5c4f0d"),
// 8-bit iv w/ 128-bit tag, 13-byte plain text, 90-byte aad
new TestVector("9f79239f0904eace50784b863e723f6b",
"d9",
"bdb0bb10c87965acd34d146171",
"44db436089327726c5f01139e1f339735c9e85514ccc2f167bad728010fb34a9072a9794c8a5e7361b1d0dbcdc9ac4091e354bb2896561f0486645252e9c78c86beece91bfa4f7cc4a8794ce1f305b1b735efdbf1ed1563c0be0",
"7e5a7c8dadb3f0c7335b4d9d8d",
"6b6ef1f53723a89f3bb7c6d043840717"),
// 1024-bit iv w/ 128-bit tag, 51-byte plain text, 48-byte aad
new TestVector("141f1ce91989b07e7eb6ae1dbd81ea5e",
"49451da24bd6074509d3cebc2c0394c972e6934b45a1d91f3ce1d3ca69e194aa1958a7c21b6f21d530ce6d2cc5256a3f846b6f9d2f38df0102c4791e57df038f6e69085646007df999751e248e06c47245f4cd3b8004585a7470dee1690e9d2d63169a58d243c0b57b3e5b4a481a3e4e8c60007094ef3adea2e8f05dd3a1396f",
"d384305af2388699aa302f510913fed0f2cb63ba42efa8c5c9de2922a2ec2fe87719dadf1eb0aef212b51e74c9c5b934104a43",
"630cf18a91cc5a6481ac9eefd65c24b1a3c93396bd7294d6b8ba323951727666c947a21894a079ef061ee159c05beeb4",
"f4c34e5fbe74c0297313268296cd561d59ccc95bbfcdfcdc71b0097dbd83240446b28dc088abd42b0fc687f208190ff24c0548",
"dbb93bbb56d0439cd09f620a57687f5d"),
};
public boolean execute(TestVector[] testValues, Cipher c) throws Exception {
boolean testFailed = false;
for (int i = 0; i < testValues.length; i++) {
try {
c.init(Cipher.ENCRYPT_MODE, testValues[i].key, testValues[i].spec);
c.updateAAD(testValues[i].aad);
byte[] ctPlusTag = c.doFinal(testValues[i].plainText);
c.init(Cipher.DECRYPT_MODE, testValues[i].key, testValues[i].spec);
c.updateAAD(testValues[i].aad);
byte[] pt = c.doFinal(ctPlusTag); // should fail if tag mismatched
// check encryption/decryption results just to be sure
if (!Arrays.equals(testValues[i].plainText, pt)) {
System.out.println("PlainText diff failed for test# " + i);
testFailed = true;
}
int ctLen = testValues[i].cipherText.length;
if (!Arrays.equals(testValues[i].cipherText,
Arrays.copyOf(ctPlusTag, ctLen))) {
System.out.println("CipherText diff failed for test# " + i);
testFailed = true;
}
int tagLen = testValues[i].tag.length;
if (!Arrays.equals
(testValues[i].tag,
Arrays.copyOfRange(ctPlusTag, ctLen, ctLen+tagLen))) {
System.out.println("Tag diff failed for test# " + i);
testFailed = true;
}
} catch (Exception ex) {
// continue testing other test vectors
System.out.println("Failed Test Vector: " + testValues[i]);
ex.printStackTrace();
testFailed = true;
continue;
}
}
if (testFailed) {
throw new Exception("Test Failed");
}
// passed all tests...hooray!
return true;
}
public static void main(String[] args) throws Exception {
main(new TestKATForGCM(), args);
}
@Override
public void main(Provider p) throws Exception {
Cipher c;
String transformation = "AES/GCM/NoPadding";
try {
c = Cipher.getInstance(transformation, p);
} catch (GeneralSecurityException e) {
System.out.println("Skip testing " + p.getName() +
", no support for " + transformation);
return;
}
if (execute(testValues, c)) {
System.out.println("Test Passed!");
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,60 +23,74 @@
/*
* @test
* @bug 4856966
* @bug 4856966 8080462
* @summary Test the MessageDigest.update(ByteBuffer) method
* @author Andreas Sterbenz
* @library /test/lib ..
* @key randomness
* @modules jdk.crypto.cryptoki
* @run main/othervm ByteBuffers
* @run main/othervm ByteBuffers sm
*/
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.Provider;
import java.security.*;
import java.util.Arrays;
import java.util.Random;
public class ByteBuffers extends PKCS11Test {
static final String[] ALGS = {
"SHA-224", "SHA-256", "SHA-384", "SHA-512", "SHA-512/224", "SHA-512/256"
};
private static Random random = new Random();
public static void main(String[] args) throws Exception {
main(new ByteBuffers(), args);
}
@Override
public void main(Provider p) throws Exception {
if (p.getService("MessageDigest", "MD5") == null) {
System.out.println("Provider does not support MD5, skipping");
return;
}
Random random = new Random();
int n = 10 * 1024;
byte[] t = new byte[n];
random.nextBytes(t);
MessageDigest md = MessageDigest.getInstance("MD5", p);
byte[] d1 = md.digest(t);
for (String alg : ALGS) {
runTest(p, alg, t);
}
}
private void runTest(Provider p, String alg, byte[] data) throws Exception {
System.out.println("Test against " + p.getName() + " and " + alg);
MessageDigest md;
try {
md = MessageDigest.getInstance(alg, p);
} catch (NoSuchAlgorithmException e) {
System.out.println("Skip " + alg + " due to no support");
return;
}
byte[] d1 = md.digest(data);
int n = data.length;
// test 1: ByteBuffer with an accessible backing array
ByteBuffer b1 = ByteBuffer.allocate(n + 256);
b1.position(random.nextInt(256));
b1.limit(b1.position() + n);
ByteBuffer b2 = b1.slice();
b2.put(t);
b2.put(data);
b2.clear();
byte[] d2 = digest(md, b2, random);
byte[] d2 = digest(md, b2);
if (Arrays.equals(d1, d2) == false) {
throw new Exception("Test 1 failed");
}
// test 2: direct ByteBuffer
ByteBuffer b3 = ByteBuffer.allocateDirect(t.length);
b3.put(t);
ByteBuffer b3 = ByteBuffer.allocateDirect(n);
b3.put(data);
b3.clear();
byte[] d3 = digest(md, b3, random);
byte[] d3 = digest(md, b3);
if (Arrays.equals(d1, d2) == false) {
throw new Exception("Test 2 failed");
}
@ -84,14 +98,15 @@ public class ByteBuffers extends PKCS11Test {
// test 3: ByteBuffer without an accessible backing array
b2.clear();
ByteBuffer b4 = b2.asReadOnlyBuffer();
byte[] d4 = digest(md, b4, random);
byte[] d4 = digest(md, b4);
if (Arrays.equals(d1, d2) == false) {
throw new Exception("Test 3 failed");
}
System.out.println("All tests passed");
}
private static byte[] digest(MessageDigest md, ByteBuffer b, Random random) throws Exception {
private static byte[] digest(MessageDigest md, ByteBuffer b)
throws Exception {
int lim = b.limit();
b.limit(random.nextInt(lim));
md.update(b);

View File

@ -0,0 +1,87 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.*;
import java.security.spec.*;
/**
* @test
* @bug 8080462
* @summary Make sure old state is cleared when init is called again
* @library /test/lib ..
* @modules jdk.crypto.cryptoki
*/
public class InitAgainPSS extends PKCS11Test {
public static void main(String[] args) throws Exception {
main(new InitAgainPSS(), args);
}
@Override
public void main(Provider p) throws Exception {
Signature s1;
try {
s1 = Signature.getInstance("RSASSA-PSS", p);
} catch (NoSuchAlgorithmException e) {
System.out.println("Skip testing RSASSA-PSS" +
" due to no support");
return;
}
byte[] msg = "hello".getBytes();
Signature s2 = Signature.getInstance("RSASSA-PSS", p);
PSSParameterSpec params = new PSSParameterSpec("SHA-256", "MGF1",
new MGF1ParameterSpec("SHA-256"), 32,
PSSParameterSpec.TRAILER_FIELD_BC);
s1.setParameter(params);
s2.setParameter(params);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p);
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
s1.initSign(kp.getPrivate());
s1.update(msg);
s1.initSign(kp.getPrivate());
s1.update(msg);
// Data digested in s1:
// Before this fix, msg | msg
// After this fix, msg
s2.initVerify(kp.getPublic());
s2.update(msg);
s2.initVerify(kp.getPublic());
s2.update(msg);
s2.initVerify(kp.getPublic());
s2.update(msg);
// Data digested in s2:
// Before this fix, msg | msg | msg
// After this fix, msg
if (!s2.verify(s1.sign())) {
throw new Exception();
}
}
}

View File

@ -0,0 +1,132 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.*;
/**
* @test
* @bug 8080462
* @summary Ensure that PSS key and params check are implemented properly
* regardless of call sequence
* @library /test/lib ..
* @modules jdk.crypto.cryptoki
* @run main KeyAndParamCheckForPSS
*/
public class KeyAndParamCheckForPSS extends PKCS11Test {
/**
* ALGORITHM name, fixed as RSA for PKCS11
*/
private static final String KEYALG = "RSA";
private static final String SIGALG = "RSASSA-PSS";
public static void main(String[] args) throws Exception {
main(new KeyAndParamCheckForPSS(), args);
}
@Override
public void main(Provider p) throws Exception {
Signature sig;
try {
sig = Signature.getInstance(SIGALG, p);
} catch (NoSuchAlgorithmException e) {
System.out.println("Skip testing RSASSA-PSS" +
" due to no support");
return;
}
// NOTE: key length >= (digest length + 2) in bytes
// otherwise, even salt length = 0 would not work
runTest(p, 1024, "SHA-384");
runTest(p, 1040, "SHA-512");
}
private void runTest(Provider p, int keySize, String hashAlg)
throws Exception {
System.out.println("Testing [" + keySize + " " + hashAlg + "]");
// create a key pair with the supplied size
KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEYALG, p);
kpg.initialize(keySize);
KeyPair kp = kpg.generateKeyPair();
int bigSaltLen = keySize/8 - 14;
AlgorithmParameterSpec paramsBad = new PSSParameterSpec(hashAlg,
"MGF1", new MGF1ParameterSpec(hashAlg), bigSaltLen, 1);
AlgorithmParameterSpec paramsGood = new PSSParameterSpec(hashAlg,
"MGF1", new MGF1ParameterSpec(hashAlg), 0, 1);
PrivateKey priv = kp.getPrivate();
PublicKey pub = kp.getPublic();
// test#1 - setParameter then initSign
Signature sig = Signature.getInstance("RSASSA-PSS", p);
sig.setParameter(paramsBad);
try {
sig.initSign(priv);
throw new RuntimeException("Expected IKE not thrown");
} catch (InvalidKeyException ike) {
System.out.println("test#1: got expected IKE");
}
sig.setParameter(paramsGood);
sig.initSign(priv);
System.out.println("test#1: pass");
// test#2 - setParameter then initVerify
sig = Signature.getInstance("RSASSA-PSS", p);
sig.setParameter(paramsBad);
try {
sig.initVerify(pub);
throw new RuntimeException("Expected IKE not thrown");
} catch (InvalidKeyException ike) {
System.out.println("test#2: got expected IKE");
}
sig.setParameter(paramsGood);
sig.initVerify(pub);
System.out.println("test#2: pass");
// test#3 - initSign, then setParameter
sig = Signature.getInstance("RSASSA-PSS", p);
sig.initSign(priv);
try {
sig.setParameter(paramsBad);
throw new RuntimeException("Expected IAPE not thrown");
} catch (InvalidAlgorithmParameterException iape) {
System.out.println("test#3: got expected IAPE");
}
sig.setParameter(paramsGood);
System.out.println("test#3: pass");
// test#4 - initVerify, then setParameter
sig = Signature.getInstance("RSASSA-PSS", p);
sig.initVerify(pub);
try {
sig.setParameter(paramsBad);
throw new RuntimeException("Expected IAPE not thrown");
} catch (InvalidAlgorithmParameterException iape) {
System.out.println("test#4: got expected IAPE");
}
sig.setParameter(paramsGood);
System.out.println("test#4: pass");
}
}

View File

@ -0,0 +1,121 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
/*
* @test
* @bug 8080462
* @summary testing interoperability of PSS signatures of PKCS11 provider
* against SunRsaSign provider
* @library /test/lib ..
* @modules jdk.crypto.cryptoki
* @run main/othervm SigInteropPSS
*/
public class SigInteropPSS extends PKCS11Test {
private static final byte[] MSG =
"Interoperability test between SunRsaSign and SunPKCS11".getBytes();
private static final String[] DIGESTS = {
"SHA-224", "SHA-256", "SHA-384", "SHA-512"
};
public static void main(String[] args) throws Exception {
main(new SigInteropPSS(), args);
}
@Override
public void main(Provider p) throws Exception {
Signature sigPkcs11;
try {
sigPkcs11 = Signature.getInstance("RSASSA-PSS", p);
} catch (NoSuchAlgorithmException e) {
System.out.println("Skip testing RSASSA-PSS" +
" due to no support");
return;
}
Signature sigSunRsaSign =
Signature.getInstance("RSASSA-PSS", "SunRsaSign");
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p);
kpg.initialize(3072);
KeyPair kp = kpg.generateKeyPair();
boolean status;
try {
status = runTest(sigSunRsaSign, sigPkcs11, kp);
status &= runTest(sigPkcs11, sigSunRsaSign, kp);
} catch (Exception e) {
System.out.println("Unexpected exception: " + e);
e.printStackTrace(System.out);
status = false;
}
if (!status) {
throw new RuntimeException("One or more test failed");
}
System.out.println("Test passed");
}
static boolean runTest(Signature signer, Signature verifier, KeyPair kp) throws Exception {
System.out.println("\tSign using " + signer.getProvider().getName());
System.out.println("\tVerify using " + verifier.getProvider().getName());
boolean status;
for (String digestAlg : DIGESTS) {
System.out.println("\tDigest = " + digestAlg);
PSSParameterSpec params = new PSSParameterSpec(digestAlg, "MGF1",
new MGF1ParameterSpec(digestAlg), 0, 1);
try {
signer.setParameter(params);
signer.initSign(kp.getPrivate());
verifier.setParameter(params);
verifier.initVerify(kp.getPublic());
} catch (Exception e) {
System.out.println("\tERROR: unexpected ex during init" + e);
status = false;
continue;
}
try {
signer.update(MSG);
byte[] sigBytes = signer.sign();
verifier.update(MSG);
boolean isValid = verifier.verify(sigBytes);
if (isValid) {
System.out.println("\tPSS Signature verified");
} else {
System.out.println("\tERROR verifying PSS Signature");
status = false;
}
} catch (Exception e) {
System.out.println("\tERROR: unexpected ex" + e);
e.printStackTrace();
status = false;
}
}
return true;
}
}

View File

@ -0,0 +1,147 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.*;
import java.util.stream.IntStream;
/**
* @test
* @bug 8080462
* @summary Generate a RSASSA-PSS signature and verify it using PKCS11 provider
* @library /test/lib ..
* @modules jdk.crypto.cryptoki
* @run main SignatureTestPSS
*/
public class SignatureTestPSS extends PKCS11Test {
// PKCS11 does not support RSASSA-PSS keys yet
private static final String KEYALG = "RSA";
private static final String SIGALG = "RSASSA-PSS";
private static final int[] KEYSIZES = { 2048, 3072 };
private static final String[] DIGESTS = { "SHA-224", "SHA-256",
"SHA-384" , "SHA-512" };
private Provider prov;
/**
* How much times signature updated.
*/
private static final int UPDATE_TIMES_FIFTY = 50;
/**
* How much times signature initial updated.
*/
private static final int UPDATE_TIMES_HUNDRED = 100;
public static void main(String[] args) throws Exception {
main(new SignatureTestPSS(), args);
}
@Override
public void main(Provider p) throws Exception {
Signature sig;
try {
sig = Signature.getInstance(SIGALG, p);
} catch (NoSuchAlgorithmException e) {
System.out.println("Skip testing RSASSA-PSS" +
" due to no support");
return;
}
this.prov = p;
for (int i : KEYSIZES) {
runTest(i);
}
}
private void runTest(int keySize) throws Exception {
byte[] data = new byte[100];
IntStream.range(0, data.length).forEach(j -> {
data[j] = (byte) j;
});
System.out.println("[KEYSIZE = " + keySize + "]");
// create a key pair
KeyPair kpair = generateKeys(KEYALG, keySize);
test(DIGESTS, kpair.getPrivate(), kpair.getPublic(), data);
}
private void test(String[] testAlgs, PrivateKey privKey,
PublicKey pubKey, byte[] data) throws RuntimeException {
// For signature algorithm, create and verify a signature
for (String testAlg : testAlgs) {
try {
checkSignature(data, pubKey, privKey, testAlg);
} catch (NoSuchAlgorithmException | InvalidKeyException |
SignatureException | NoSuchProviderException ex) {
throw new RuntimeException(ex);
} catch (InvalidAlgorithmParameterException ex2) {
System.out.println("Skip test due to " + ex2);
}
};
}
private KeyPair generateKeys(String keyalg, int size)
throws NoSuchAlgorithmException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyalg, prov);
kpg.initialize(size);
return kpg.generateKeyPair();
}
private void checkSignature(byte[] data, PublicKey pub,
PrivateKey priv, String mdAlg) throws NoSuchAlgorithmException,
InvalidKeyException, SignatureException, NoSuchProviderException,
InvalidAlgorithmParameterException {
System.out.println("Testing against " + mdAlg);
Signature sig = Signature.getInstance(SIGALG, prov);
AlgorithmParameterSpec params = new PSSParameterSpec(
mdAlg, "MGF1", new MGF1ParameterSpec(mdAlg), 0, 1);
sig.setParameter(params);
sig.initSign(priv);
for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) {
sig.update(data);
}
byte[] signedData = sig.sign();
// Make sure signature verifies with original data
// do we need to call sig.setParameter(params) again?
sig.initVerify(pub);
for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) {
sig.update(data);
}
if (!sig.verify(signedData)) {
throw new RuntimeException("Failed to verify signature");
}
// Make sure signature does NOT verify when the original data
// has changed
sig.initVerify(pub);
for (int i = 0; i < UPDATE_TIMES_FIFTY; i++) {
sig.update(data);
}
if (sig.verify(signedData)) {
throw new RuntimeException("Failed to detect bad signature");
}
}
}

View File

@ -0,0 +1,93 @@
/*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8080462
* @library /test/lib ..
* @modules jdk.crypto.cryptoki
* @run main/othervm/timeout=250 TestDSA2
* @summary verify that DSA signature works using SHA-2 digests.
* @key randomness
*/
import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
public class TestDSA2 extends PKCS11Test {
private static final String[] SIG_ALGOS = {
"SHA224withDSA",
"SHA256withDSA",
//"SHA384withDSA",
//"SHA512withDSA",
};
private static final int KEYSIZE = 2048;
public static void main(String[] args) throws Exception {
main(new TestDSA2(), args);
}
@Override
public void main(Provider p) throws Exception {
KeyPair kp;
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA", p);
kpg.initialize(KEYSIZE);
kp = kpg.generateKeyPair();
} catch (Exception ex) {
System.out.println("Skip due to no 2048-bit DSA support: " + ex);
ex.printStackTrace();
return;
}
for (String sigAlg : SIG_ALGOS) {
test(sigAlg, kp, p);
}
}
private static void test(String sigAlg, KeyPair kp, Provider p)
throws Exception {
Signature sig;
try {
sig = Signature.getInstance(sigAlg, p);
} catch (Exception ex) {
System.out.println("Skip due to no support: " + sigAlg);
ex.printStackTrace();
return;
}
byte[] data = "anything will do".getBytes();
sig.initSign(kp.getPrivate());
sig.update(data);
byte[] signature = sig.sign();
sig.initVerify(kp.getPublic());
sig.update(data);
boolean verifies = sig.verify(signature);
System.out.println(sigAlg + ": Passed");
}
}