下面列出了怎么用java.security.spec.InvalidParameterSpecException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
*
* @param publickeybytes
* @return
* @throws java.security.spec.InvalidKeySpecException
* @throws java.security.NoSuchAlgorithmException
* @throws java.security.NoSuchProviderException
* @throws java.security.spec.InvalidParameterSpecException
*/
public static ECPublicKey getUserECPublicKey(byte[] publickeybytes) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, InvalidParameterSpecException {
//append the sign byte to the arrays
byte[] processedXData = new byte[EC_POINTSIZE];
byte[] processedYData = new byte[EC_POINTSIZE];
System.arraycopy(publickeybytes, 1, processedXData, 0, EC_POINTSIZE);
System.arraycopy(publickeybytes, EC_POINTSIZE + 1, processedYData, 0, EC_POINTSIZE);
ECPoint pubPoint = new ECPoint(new BigInteger(1, processedXData), new BigInteger(1, processedYData));
AlgorithmParameters params = AlgorithmParameters.getInstance("EC", BC_FIPS_PROVIDER);
params.init(new ECGenParameterSpec("prime256v1"));
ECParameterSpec ecParameters = params.getParameterSpec(ECParameterSpec.class);
ECPublicKeySpec pubECSpec = new ECPublicKeySpec(pubPoint, ecParameters);
return (ECPublicKey) KeyFactory.getInstance("EC", BC_FIPS_PROVIDER).generatePublic(pubECSpec);
}
static ECGenParameterSpec getECGenParamSpec(NamedGroup namedGroup) {
if (namedGroup.type != NamedGroupType.NAMED_GROUP_ECDHE) {
throw new RuntimeException(
"Not a named EC group: " + namedGroup);
}
AlgorithmParameters params = namedGroupParams.get(namedGroup);
if (params == null) {
throw new RuntimeException(
"Not a supported EC named group: " + namedGroup);
}
try {
return params.getParameterSpec(ECGenParameterSpec.class);
} catch (InvalidParameterSpecException ipse) {
// should be unlikely
return new ECGenParameterSpec(namedGroup.oid);
}
}
private static void testDSAGenParameterSpec(DataTuple dataTuple)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidParameterSpecException, InvalidAlgorithmParameterException {
System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n",
dataTuple.primePLen, dataTuple.subprimeQLen);
AlgorithmParameterGenerator apg
= AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME,
PROVIDER_NAME);
DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
// genParamSpec will be null if IllegalAE is thrown when expected.
if (genParamSpec == null) {
return;
}
try {
apg.init(genParamSpec, null);
AlgorithmParameters param = apg.generateParameters();
checkParam(param, genParamSpec);
System.out.println("Test case passed");
} catch (InvalidParameterException ipe) {
throw new RuntimeException("Test case failed.", ipe);
}
}
/**
* Initialize the ChaCha20Poly1305Parameters using an IvParameterSpec.
*
* @param paramSpec the {@code IvParameterSpec} used to configure
* this object.
*
* @throws InvalidParameterSpecException if an object of a type other
* than {@code IvParameterSpec} is used.
*/
@Override
protected void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException {
if (!(paramSpec instanceof IvParameterSpec)) {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
IvParameterSpec ivps = (IvParameterSpec)paramSpec;
// Obtain the nonce
nonce = ivps.getIV();
if (nonce.length != 12) {
throw new InvalidParameterSpecException("ChaCha20-Poly1305 nonce" +
" must be 12 bytes in length");
}
}
private void checkCryptoPerm(CipherSpi checkSpi, Key key,
AlgorithmParameters params)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (cryptoPerm == CryptoAllPermission.INSTANCE) {
return;
}
// Convert the specified parameters into specs and then delegate.
AlgorithmParameterSpec pSpec;
try {
pSpec = getAlgorithmParameterSpec(params);
} catch (InvalidParameterSpecException ipse) {
throw new InvalidAlgorithmParameterException
("Failed to retrieve algorithm parameter specification");
}
checkCryptoPerm(checkSpi, key, pSpec);
}
/**
* Returns the DSA parameters associated with this key, or null if the
* parameters could not be parsed.
*/
public DSAParams getParams() {
try {
if (algid instanceof DSAParams) {
return (DSAParams)algid;
} else {
DSAParameterSpec paramSpec;
AlgorithmParameters algParams = algid.getParameters();
if (algParams == null) {
return null;
}
paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
return (DSAParams)paramSpec;
}
} catch (InvalidParameterSpecException e) {
return null;
}
}
protected <T extends AlgorithmParameterSpec>
T engineGetParameterSpec(Class<T> paramSpec)
throws InvalidParameterSpecException
{
try {
Class<?> dsaParamSpec = Class.forName
("java.security.spec.DSAParameterSpec");
if (dsaParamSpec.isAssignableFrom(paramSpec)) {
return paramSpec.cast(
new DSAParameterSpec(this.p, this.q, this.g));
} else {
throw new InvalidParameterSpecException
("Inappropriate parameter Specification");
}
} catch (ClassNotFoundException e) {
throw new InvalidParameterSpecException
("Unsupported parameter specification: " + e.getMessage());
}
}
/**
* Returns the DSA parameters associated with this key, or null if the
* parameters could not be parsed.
*/
public DSAParams getParams() {
try {
if (algid instanceof DSAParams) {
return (DSAParams)algid;
} else {
DSAParameterSpec paramSpec;
AlgorithmParameters algParams = algid.getParameters();
if (algParams == null) {
return null;
}
paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
return (DSAParams)paramSpec;
}
} catch (InvalidParameterSpecException e) {
return null;
}
}
protected void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException {
if (!(paramSpec instanceof RC2ParameterSpec)) {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
RC2ParameterSpec rps = (RC2ParameterSpec) paramSpec;
// check effective key size (a value of 0 means it is unspecified)
effectiveKeySize = rps.getEffectiveKeyBits();
if (effectiveKeySize != 0) {
if (effectiveKeySize < 1 || effectiveKeySize > 1024) {
throw new InvalidParameterSpecException("RC2 effective key " +
"size must be between 1 and 1024 bits");
}
if (effectiveKeySize < 256) {
version = EKB_TABLE[effectiveKeySize];
} else {
version = effectiveKeySize;
}
}
this.iv = rps.getIV();
}
protected AlgorithmParameters engineGetParameters() {
if (spec != null && spec instanceof OAEPParameterSpec) {
try {
AlgorithmParameters params =
AlgorithmParameters.getInstance("OAEP",
SunJCE.getInstance());
params.init(spec);
return params;
} catch (NoSuchAlgorithmException nsae) {
// should never happen
throw new RuntimeException("Cannot find OAEP " +
" AlgorithmParameters implementation in SunJCE provider");
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new RuntimeException("OAEPParameterSpec not supported");
}
} else {
return null;
}
}
protected void engineInit(int opmode, Key key,
AlgorithmParameters params, SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (params == null) {
init(opmode, key, random, null);
} else {
try {
OAEPParameterSpec spec =
params.getParameterSpec(OAEPParameterSpec.class);
init(opmode, key, random, spec);
} catch (InvalidParameterSpecException ipse) {
InvalidAlgorithmParameterException iape =
new InvalidAlgorithmParameterException("Wrong parameter");
iape.initCause(ipse);
throw iape;
}
}
}
protected void engineInit(int opmode, Key key,
AlgorithmParameters params, SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (params == null) {
init(opmode, key, random, null);
} else {
try {
OAEPParameterSpec spec =
params.getParameterSpec(OAEPParameterSpec.class);
init(opmode, key, random, spec);
} catch (InvalidParameterSpecException ipse) {
InvalidAlgorithmParameterException iape =
new InvalidAlgorithmParameterException("Wrong parameter");
iape.initCause(ipse);
throw iape;
}
}
}
private void checkCryptoPerm(CipherSpi checkSpi, Key key,
AlgorithmParameters params)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (cryptoPerm == CryptoAllPermission.INSTANCE) {
return;
}
// Convert the specified parameters into specs and then delegate.
AlgorithmParameterSpec pSpec;
try {
pSpec = getAlgorithmParameterSpec(params);
} catch (InvalidParameterSpecException ipse) {
throw new InvalidAlgorithmParameterException
("Failed to retrieve algorithm parameter specification");
}
checkCryptoPerm(checkSpi, key, pSpec);
}
private AlgorithmParameterSpec getAlgorithmParameterSpec(
AlgorithmParameters params)
throws InvalidParameterSpecException {
if (params == null) {
return null;
}
String alg = params.getAlgorithm().toUpperCase(Locale.ENGLISH);
if (alg.equalsIgnoreCase("RC2")) {
return params.getParameterSpec(RC2ParameterSpec.class);
}
if (alg.equalsIgnoreCase("RC5")) {
return params.getParameterSpec(RC5ParameterSpec.class);
}
if (alg.startsWith("PBE")) {
return params.getParameterSpec(PBEParameterSpec.class);
}
if (alg.startsWith("DES")) {
return params.getParameterSpec(IvParameterSpec.class);
}
return null;
}
private static void testDSAGenParameterSpec(DataTuple dataTuple)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidParameterSpecException, InvalidAlgorithmParameterException {
System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n",
dataTuple.primePLen, dataTuple.subprimeQLen);
AlgorithmParameterGenerator apg
= AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME,
PROVIDER_NAME);
DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
// genParamSpec will be null if IllegalAE is thrown when expected.
if (genParamSpec == null) {
return;
}
try {
apg.init(genParamSpec, null);
AlgorithmParameters param = apg.generateParameters();
checkParam(param, genParamSpec);
System.out.println("Test case passed");
} catch (InvalidParameterException ipe) {
throw new RuntimeException("Test case failed.", ipe);
}
}
private void checkCryptoPerm(CipherSpi checkSpi, Key key)
throws InvalidKeyException {
if (cryptoPerm == CryptoAllPermission.INSTANCE) {
return;
}
// Check if key size and default parameters are within legal limits
AlgorithmParameterSpec params;
try {
params = getAlgorithmParameterSpec(checkSpi.engineGetParameters());
} catch (InvalidParameterSpecException ipse) {
throw new InvalidKeyException
("Unsupported default algorithm parameters");
}
if (!passCryptoPermCheck(checkSpi, key, params)) {
throw new InvalidKeyException(
"Illegal key size or default parameters");
}
}
protected <T extends AlgorithmParameterSpec>
T engineGetParameterSpec(Class<T> paramSpec)
throws InvalidParameterSpecException
{
try {
Class<?> dsaParamSpec = Class.forName
("java.security.spec.DSAParameterSpec");
if (dsaParamSpec.isAssignableFrom(paramSpec)) {
return paramSpec.cast(
new DSAParameterSpec(this.p, this.q, this.g));
} else {
throw new InvalidParameterSpecException
("Inappropriate parameter Specification");
}
} catch (ClassNotFoundException e) {
throw new InvalidParameterSpecException
("Unsupported parameter specification: " + e.getMessage());
}
}
/**
* Returns the DSA parameters associated with this key, or null if the
* parameters could not be parsed.
*/
public DSAParams getParams() {
try {
if (algid instanceof DSAParams) {
return (DSAParams)algid;
} else {
DSAParameterSpec paramSpec;
AlgorithmParameters algParams = algid.getParameters();
if (algParams == null) {
return null;
}
paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
return (DSAParams)paramSpec;
}
} catch (InvalidParameterSpecException e) {
return null;
}
}
protected void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException {
if (!(paramSpec instanceof RC2ParameterSpec)) {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
RC2ParameterSpec rps = (RC2ParameterSpec) paramSpec;
// check effective key size (a value of 0 means it is unspecified)
effectiveKeySize = rps.getEffectiveKeyBits();
if (effectiveKeySize != 0) {
if (effectiveKeySize < 1 || effectiveKeySize > 1024) {
throw new InvalidParameterSpecException("RC2 effective key " +
"size must be between 1 and 1024 bits");
}
if (effectiveKeySize < 256) {
version = EKB_TABLE[effectiveKeySize];
} else {
version = effectiveKeySize;
}
}
this.iv = rps.getIV();
}
private FIDO2AttestationObject retrieveAttestationObjectFromFIDOResponseObject(JsonObject response){
try {
String attestationObjectString = response.getString(skfsConstants.JSON_KEY_ATTESTATIONOBJECT);
FIDO2AttestationObject attObject = new FIDO2AttestationObject();
attObject.decodeAttestationObject(attestationObjectString);
return attObject;
} catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException | InvalidParameterSpecException ex) {
skfsLogger.log(skfsConstants.SKFE_LOGGER,Level.FINE, "FIDO-ERR-5011", "Invalid attestaionObject: " + ex);
throw new SKIllegalArgumentException("Invalid attestaionObject");
}
}
public static ECPublicKey getUserECPublicKey(byte[] x, byte[] y, String curveString) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, InvalidParameterSpecException {
//append the sign byte to the arrays
ECPoint pubPoint = new ECPoint(new BigInteger(1, x), new BigInteger(1, y));
AlgorithmParameters params = AlgorithmParameters.getInstance("EC", BC_FIPS_PROVIDER);
params.init(new ECGenParameterSpec(curveString));
ECParameterSpec ecParameters = params.getParameterSpec(ECParameterSpec.class);
ECPublicKeySpec pubECSpec = new ECPublicKeySpec(pubPoint, ecParameters);
return (ECPublicKey) KeyFactory.getInstance("EC", BC_FIPS_PROVIDER).generatePublic(pubECSpec);
}
/**
* Function to make a key-handle for transporting to the FIDO U2F server
*
* @param pvk PrivateKey of the ECDSA key-pair
* @param originHash String Message digest of the origin for which this
* private-key is valid
* @return String Base64-encoded key-handle
*
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
* @throws FileNotFoundException
* @throws DecoderException
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidAlgorithmParameterException
* @throws ShortBufferException
* @throws InvalidKeySpecException
* @throws SignatureException
* @throws java.security.spec.InvalidParameterSpecException
*/
public static String makeKeyHandle(PrivateKey pvk, String originHash)
throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, FileNotFoundException, DecoderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException, ShortBufferException, InvalidKeySpecException, SignatureException, InvalidParameterSpecException {
// Get wrapping key
byte[] Seckeybytes = Hex.decodeHex(Constants.FIXED_AES256_WRAPPING_KEY.toCharArray());
SecretKeySpec sks = new SecretKeySpec(Seckeybytes, "AES");
ECPrivateKey ecpk = (ECPrivateKey) pvk;
byte[] s = org.bouncycastle.util.encoders.Hex.decode(String.format("%064x", ecpk.getS()));
// Encode plaintext key-handle into JSON structure
String ptkh = encodeKeyHandle(Base64.getUrlEncoder().encodeToString(s), originHash, getDigest(pvk.getEncoded(), "SHA1"));
// System.out.println("PlaintextKeyHandle: " + ptkh);
// Encrypt key handle to create ciphertext
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BCFIPS");
cipher.init(Cipher.ENCRYPT_MODE, sks, new SecureRandom());
byte[] ctkh = cipher.doFinal(ptkh.getBytes("UTF-8"));
// Recover IV from cipher and prepend to encrypted keyhandle in new array
byte[] iv = cipher.getIV();
byte[] ctkhiv = new byte[ctkh.length + Constants.ENCRYPTION_MODE_CBC_IV_LENGTH];
System.arraycopy(iv, 0, ctkhiv, 0, Constants.ENCRYPTION_MODE_CBC_IV_LENGTH); // Copy IV to new array
System.arraycopy(ctkh, 0, ctkhiv, Constants.ENCRYPTION_MODE_CBC_IV_LENGTH, ctkh.length); // Append ciphertext KH to IV
// Base64-encode ciphertext keyhandle + IV
String ctkhivb64 = Base64.getUrlEncoder().encodeToString(ctkhiv);
// Test recovery of plaintext key-handle before returning
//String ptkh2 = decryptKeyHandle(ctkhivb64);
//if (!ptkh2.trim().equalsIgnoreCase(ptkh.trim())) {
// System.err.println("Decryption of keyhandle failed during test");
// return null;
//}
// Decryption succeeded - return Base64-encoded, encrypted keyhandle + IV
return ctkhivb64;
}
protected <T extends AlgorithmParameterSpec>
T engineGetParameterSpec(Class<T> paramSpec)
throws InvalidParameterSpecException
{
if (PBEParameterSpec.class.isAssignableFrom(paramSpec)) {
return paramSpec.cast(
new PBEParameterSpec(this.salt, this.iCount, this.cipherParam));
} else {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
}
/**
* Function to generate a PrivateKey object from a byte-array containing the
* ECDSA private-key
*
* @param pvk String with Base64-encoded private key
* @return PrivateKey
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidKeySpecException
* @throws java.security.spec.InvalidParameterSpecException
*/
public static PrivateKey getUserPrivateKey(String pvk)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeySpecException, InvalidParameterSpecException
{
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec("secp256r1"));
ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(1, Base64.getUrlDecoder().decode(pvk)), ecParameterSpec);
return KeyFactory.getInstance("EC").generatePrivate(ecPrivateKeySpec);
}
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;
this.iv = gps.getIV();
}
public static ECParameterSpec getParameterSpec() {
try {
return Holder.INSTANCE.getParameterSpec(ECParameterSpec.class);
} catch (InvalidParameterSpecException ex) {
throw new AssertionError(
"Assumed correct key spec statically");
}
}
protected <T extends AlgorithmParameterSpec>
T engineGetParameterSpec(Class<T> paramSpec)
throws InvalidParameterSpecException
{
if (PBEParameterSpec.class.isAssignableFrom(paramSpec)) {
return paramSpec.cast(
new PBEParameterSpec(this.salt, this.iCount, this.cipherParam));
} else {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
}
protected <T extends AlgorithmParameterSpec>
T engineGetParameterSpec(Class<T> paramSpec)
throws InvalidParameterSpecException {
if (AlgorithmParameterSpec.class.isAssignableFrom(paramSpec)) {
return core.getParameterSpec(paramSpec);
} else {
throw new InvalidParameterSpecException
("Inappropriate parameter Specification");
}
}
protected void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException {
if (!(paramSpec instanceof DSAParameterSpec)) {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
this.p = ((DSAParameterSpec)paramSpec).getP();
this.q = ((DSAParameterSpec)paramSpec).getQ();
this.g = ((DSAParameterSpec)paramSpec).getG();
}
protected <T extends AlgorithmParameterSpec>
T engineGetParameterSpec(Class<T> paramSpec)
throws InvalidParameterSpecException {
if (AlgorithmParameterSpec.class.isAssignableFrom(paramSpec)) {
return core.getParameterSpec(paramSpec);
} else {
throw new InvalidParameterSpecException
("Inappropriate parameter Specification");
}
}