下面列出了java.security.spec.ECGenParameterSpec#java.security.spec.InvalidKeySpecException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public ElexisEnvironmentLoginDialog(Shell shell, String openidClientSecret, String keycloakUrl,
String realmPublicKey){
super(shell);
logger = LoggerFactory.getLogger(getClass());
oauthService = new ServiceBuilder(ElexisEnvironmentLoginContributor.OAUTH2_CLIENT_ID)
.apiSecret(openidClientSecret).defaultScope("openid").callback(CALLBACK_URL)
.build(KeycloakApi.instance(keycloakUrl, ElexisEnvironmentLoginContributor.REALM_ID));
KeyFactory kf;
try {
kf = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpecX509 =
new X509EncodedKeySpec(Base64.getDecoder().decode(realmPublicKey));
RSAPublicKey publicKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
jwtParser = Jwts.parserBuilder().setSigningKey(publicKey).build();
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
logger.error("Initialization error", e);
}
}
protected PublicKey engineGeneratePublic(
KeySpec keySpec)
throws InvalidKeySpecException
{
if (keySpec instanceof X509EncodedKeySpec)
{
try
{
SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(((X509EncodedKeySpec)keySpec).getEncoded());
PublicKey key = BouncyCastleProvider.getPublicKey(info);
if (key != null)
{
return key;
}
throw new InvalidKeySpecException("no factory found for OID: " + info.getAlgorithm().getAlgorithm());
}
catch (Exception e)
{
throw new InvalidKeySpecException(e.toString());
}
}
throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}
/**
* Generates a <code>SecretKey</code> object from the provided key
* specification (key material).
*
* @param keySpec the specification (key material) of the secret key
*
* @return the secret key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a public key.
*/
protected SecretKey engineGenerateSecret(KeySpec keySpec)
throws InvalidKeySpecException {
try {
if (keySpec instanceof DESedeKeySpec) {
return new DESedeKey(((DESedeKeySpec)keySpec).getKey());
}
if (keySpec instanceof SecretKeySpec) {
return new DESedeKey(((SecretKeySpec)keySpec).getEncoded());
}
throw new InvalidKeySpecException
("Inappropriate key specification");
} catch (InvalidKeyException e) {
throw new InvalidKeySpecException(e.getMessage());
}
}
/**
* The key is generating by SecretKeyFactory and its value just copying
* in the key field of MySecretKey class. So, this is real key derived
* using the given algo.
*/
public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt1,
int iterationCount, int keySize)
throws InvalidKeySpecException, NoSuchAlgorithmException {
algorithm = algo;
salt = salt1;
itereationCount = iterationCount;
pass = passPhrase;
PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt,
iterationCount, keySize);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo);
SecretKey realKey = keyFactory.generateSecret(spec);
keyLength = realKey.getEncoded().length;
key = new byte[keyLength];
System.arraycopy(realKey.getEncoded(), 0, key, 0, keyLength);
}
/**
* Test.
*
* @throws NoSuchAlgorithmException the no such algorithm exception
* @throws UnsupportedEncodingException the unsupported encoding exception
* @throws InvalidKeySpecException the invalid key spec exception
*/
@Test
public void test() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
EncryptionUtil util = EncryptionUtil.getInstance("1234", "abcd");
String raw = "testRaw";
try {
String encrypt = util.encrypt(raw);
Assert.assertNotNull(encrypt);
String decrypt = util.decrypt(encrypt);
Assert.assertNotNull(decrypt);
Assert.assertEquals(raw, decrypt);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, String password, byte[] salt, boolean encryptMode)
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException {
if (encryptionMethod == null) {
throw new IllegalArgumentException("The encryption method must be specified");
}
if (StringUtils.isEmpty(password)) {
throw new IllegalArgumentException("Encryption with an empty password is not supported");
}
validateSalt(encryptionMethod, salt);
String algorithm = encryptionMethod.getAlgorithm();
String provider = encryptionMethod.getProvider();
// Initialize secret key from password
final PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm, provider);
SecretKey tempKey = factory.generateSecret(pbeKeySpec);
final PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, getIterationCount());
Cipher cipher = Cipher.getInstance(algorithm, provider);
cipher.init(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, tempKey, parameterSpec);
return cipher;
}
protected PublicKey engineGeneratePublic(
KeySpec keySpec)
throws InvalidKeySpecException
{
if (keySpec instanceof X509EncodedKeySpec)
{
try
{
SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(((X509EncodedKeySpec)keySpec).getEncoded());
PublicKey key = BouncyCastleProvider.getPublicKey(info);
if (key != null)
{
return key;
}
throw new InvalidKeySpecException("no factory found for OID: " + info.getAlgorithm().getAlgorithm());
}
catch (Exception e)
{
throw new InvalidKeySpecException(e.toString());
}
}
throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}
private PublicKey getPublicKey(P11ObjectIdentifier objectId)
throws P11UnknownEntityException, P11TokenException {
ASN1Object req =
new ProxyMessage.SlotIdAndObjectId(asn1SlotId, new ProxyMessage.ObjectIdentifier(objectId));
byte[] resp = module.send(P11ProxyConstants.ACTION_GET_PUBLICKEY, req);
if (resp == null) {
return null;
}
SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfo.getInstance(resp);
try {
return KeyUtil.generatePublicKey(pkInfo);
} catch (InvalidKeySpecException ex) {
throw new P11TokenException("could not generate Public Key from SubjectPublicKeyInfo:"
+ ex.getMessage(), ex);
}
}
/**
* Generates a private key object from the provided key specification
* (key material).
*
* @param keySpec the specification (key material) of the private key
*
* @return the private key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a private key.
*/
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
try {
if (keySpec instanceof DSAPrivateKeySpec) {
DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
return new DSAPrivateKey(dsaPrivKeySpec.getX(),
dsaPrivKeySpec.getP(),
dsaPrivKeySpec.getQ(),
dsaPrivKeySpec.getG());
} else if (keySpec instanceof PKCS8EncodedKeySpec) {
return new DSAPrivateKey
(((PKCS8EncodedKeySpec)keySpec).getEncoded());
} else {
throw new InvalidKeySpecException
("Inappropriate key specification");
}
} catch (InvalidKeyException e) {
throw new InvalidKeySpecException
("Inappropriate key specification: " + e.getMessage());
}
}
static String generateAesKeyName(Context context)
throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
final char[] password = context.getPackageName()
.toCharArray();
final byte[] salt = getDeviceSerialNumber(context).getBytes();
SecretKey key;
try {
// what if there's an OS upgrade and now supports the primary
// PBE
key = generatePBEKey(password, salt, PRIMARY_PBE_KEY_ALG, ITERATIONS, KEY_SIZE);
} catch (NoSuchAlgorithmException e) {
// older devices may not support the have the implementation,
// try with a weaker algorithm
key = generatePBEKey(password, salt, BACKUP_PBE_KEY_ALG, ITERATIONS, KEY_SIZE);
}
return encode(key.getEncoded());
}
/** Create a Cloud IoT Core JWT for the given project id, signed with the given ES key. */
private static String createJwtEs(String projectId, String privateKeyFile)
throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
DateTime now = new DateTime();
// Create a JWT to authenticate this device. The device will be disconnected after the token
// expires, and will have to reconnect with a new token. The audience field should always be set
// to the GCP project id.
JwtBuilder jwtBuilder =
Jwts.builder()
.setIssuedAt(now.toDate())
.setExpiration(now.plusMinutes(20).toDate())
.setAudience(projectId);
byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("EC");
return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact();
}
/**
* Returns a specification (key material) of the given key
* in the requested format.
*
* @param key the key
*
* @param keySpec the requested format in which the key material shall be
* returned
*
* @return the underlying key specification (key material) in the
* requested format
*
* @exception InvalidKeySpecException if the requested key
* specification is inappropriate for the given key, or the
* given key cannot be processed (e.g., the given key has an
* unrecognized algorithm or format).
*/
protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
throws InvalidKeySpecException {
if (key instanceof javax.crypto.interfaces.PBEKey) {
// Check if requested key spec is amongst the valid ones
if ((keySpecCl != null)
&& PBEKeySpec.class.isAssignableFrom(keySpecCl)) {
javax.crypto.interfaces.PBEKey pKey =
(javax.crypto.interfaces.PBEKey) key;
return new PBEKeySpec
(pKey.getPassword(), pKey.getSalt(),
pKey.getIterationCount(), pKey.getEncoded().length*8);
} else {
throw new InvalidKeySpecException("Invalid key spec");
}
} else {
throw new InvalidKeySpecException("Invalid key " +
"format/algorithm");
}
}
/**
* Returns a specification (key material) of the given key
* in the requested format.
*
* @param key the key
*
* @param keySpec the requested format in which the key material shall be
* returned
*
* @return the underlying key specification (key material) in the
* requested format
*
* @exception InvalidKeySpecException if the requested key
* specification is inappropriate for the given key, or the
* given key cannot be processed (e.g., the given key has an
* unrecognized algorithm or format).
*/
protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
throws InvalidKeySpecException {
if (key instanceof javax.crypto.interfaces.PBEKey) {
// Check if requested key spec is amongst the valid ones
if ((keySpecCl != null)
&& PBEKeySpec.class.isAssignableFrom(keySpecCl)) {
javax.crypto.interfaces.PBEKey pKey =
(javax.crypto.interfaces.PBEKey) key;
return new PBEKeySpec
(pKey.getPassword(), pKey.getSalt(),
pKey.getIterationCount(), pKey.getEncoded().length*8);
} else {
throw new InvalidKeySpecException("Invalid key spec");
}
} else {
throw new InvalidKeySpecException("Invalid key " +
"format/algorithm");
}
}
private KeyPair createKeyPair() throws InvalidKeySpecException, NoSuchAlgorithmException {
final RSAKeyPairGenerator gen = new RSAKeyPairGenerator();
gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(3), new SecureRandom(), 1024, 80));
final AsymmetricCipherKeyPair keypair = gen.generateKeyPair();
final RSAKeyParameters publicKey = (RSAKeyParameters) keypair.getPublic();
final RSAPrivateCrtKeyParameters privateKey = (RSAPrivateCrtKeyParameters) keypair.getPrivate();
final PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic(
new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent()));
final PrivateKey privKey = KeyFactory.getInstance("RSA").generatePrivate(
new RSAPrivateCrtKeySpec(publicKey.getModulus(), publicKey.getExponent(),
privateKey.getExponent(), privateKey.getP(), privateKey.getQ(),
privateKey.getDP(), privateKey.getDQ(), privateKey.getQInv()));
return new KeyPair(pubKey, privKey);
}
/**
* Loads the private key of this process
*
* @return the PrivateKey loaded from config/keys/publickey<conf.getProcessId()>
* @throws Exception problems reading or parsing the key
*/
public PrivateKey loadPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
if (defaultKeys) {
return getPrivateKeyFromString(RSAKeyLoader.DEFAULT_PKEY);
}
if (priKey == null) {
FileReader f = new FileReader(path + "privatekey" + this.id);
BufferedReader r = new BufferedReader(f);
String tmp = "";
String key = "";
while ((tmp = r.readLine()) != null) {
key = key + tmp;
}
f.close();
r.close();
priKey = getPrivateKeyFromString(key);
}
return priKey;
}
/**
* generates a secret key from the passed in raw key value
* we create a 256 bit key that is salted using our example
* salt value above
*
* @param key input key in a char array
* @return a salted key of the type SECRET_KEY_TYPE
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
* @throws InvalidKeySpecException
*/
private static SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException,
UnsupportedEncodingException,
InvalidKeySpecException,
NoSuchProviderException
{
SecretKeyFactory factory = null;
factory = SecretKeyFactory.getInstance(SECRET_KEY_TYPE,
SECURITY_PROVIDER);
KeySpec spec = new PBEKeySpec(key,
salt.getBytes("UTF-8"),
ITERATION_COUNT,
KEY_LENGTH);
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), AES);
}
@VisibleForTesting
static PublicKey decodePublicKey(byte[] keyBytes)
throws NoSuchAlgorithmException, InvalidKeyException {
BigInteger x =
new BigInteger(
/*signum=*/ 1,
Arrays.copyOfRange(keyBytes, 1, 1 + EC_COORDINATE_LEN_BYTES));
BigInteger y =
new BigInteger(
/*signum=*/ 1,
Arrays.copyOfRange(
keyBytes, 1 + EC_COORDINATE_LEN_BYTES, EC_PUBLIC_KEY_LEN_BYTES));
// Checks if the point is indeed on the P-256 curve for security considerations
validateEcPoint(x, y);
KeyFactory keyFactory = KeyFactory.getInstance(EC_ALG);
try {
return keyFactory.generatePublic(new ECPublicKeySpec(new ECPoint(x, y), EC_PARAM_SPEC));
} catch (InvalidKeySpecException ex) {
// This should never happen
throw new RuntimeException(ex);
}
}
/**
* Tulio A. Ribeiro.
* @return SecretKey
*/
public SecretKey getSecretKey() {
if (secretKey != null)
return secretKey;
else {
SecretKeyFactory fac;
PBEKeySpec spec;
try {
fac = TOMUtil.getSecretFactory();
spec = TOMUtil.generateKeySpec(SECRET.toCharArray());
secretKey = fac.generateSecret(spec);
} catch (NoSuchAlgorithmException |InvalidKeySpecException e) {
logger.error("Algorithm error.",e);
}
}
return secretKey;
}
public static RSAPublicKey decodeRSAPublicKey(String key) throws RSAException {
if (key == null) {
throw ExceptionFactory.createException(RSAException.class, "Key parameter is null");
}
int offset = key.indexOf("\n") + 1;
int len = key.indexOf("-----END PUBLIC KEY-----") - offset;
// TODO: use standard decoders with Java 6+
byte[] certificateData = Base64Decoder.decode(key.getBytes(), offset, len);
X509EncodedKeySpec spec = new X509EncodedKeySpec(certificateData);
try {
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPublicKey) kf.generatePublic(spec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw ExceptionFactory.createException(RSAException.class, "Unable to decode public key", e);
}
}
@Test
public void testCryptoExceptions() {
CryptoException ex = new CryptoException();
assertNotNull(ex);
assertEquals(ex.getCode(), CryptoException.CRYPTO_ERROR);
assertNotNull(new CryptoException(new NoSuchAlgorithmException()));
assertNotNull(new CryptoException(new InvalidKeyException()));
assertNotNull(new CryptoException(new NoSuchProviderException()));
assertNotNull(new CryptoException(new SignatureException()));
assertNotNull(new CryptoException(new FileNotFoundException()));
assertNotNull(new CryptoException(new IOException()));
assertNotNull(new CryptoException(new CertificateException()));
assertNotNull(new CryptoException(new InvalidKeySpecException()));
assertNotNull(new CryptoException(new OperatorCreationException("unit-test")));
assertNotNull(new CryptoException(new PKCSException("unit-test")));
assertNotNull(new CryptoException(new CMSException("unit-test")));
ex = new CryptoException(CryptoException.CERT_HASH_MISMATCH, "X.509 Certificate hash mismatch");
assertEquals(ex.getCode(), CryptoException.CERT_HASH_MISMATCH);
}
public int getKeyLength() {
final String publicKey = rsaCredentialData.getPublicKey();
if (StringUtils.isEmpty(publicKey)) {
return 0;
}
try {
final String key = publicKey
.replaceFirst(RSA_START, "")
.replaceFirst(RSA_END, "")
.replaceAll(NEW_LINE, "");
final byte[] byteKey = Base64.decodeBase64(key.getBytes(UTF_8));
final X509EncodedKeySpec x509publicKey = new X509EncodedKeySpec(byteKey);
final KeyFactory kf = KeyFactory.getInstance("RSA");
return ((RSAPublicKey) kf.generatePublic(x509publicKey)).getModulus().bitLength();
} catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new RuntimeException(e);
}
}
/**
* Generates a <code>SecretKey</code> object from the provided key
* specification (key material).
*
* @param keySpec the specification (key material) of the secret key
*
* @return the secret key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a public key.
*/
protected SecretKey engineGenerateSecret(KeySpec keySpec)
throws InvalidKeySpecException {
try {
if (keySpec instanceof DESedeKeySpec) {
return new DESedeKey(((DESedeKeySpec)keySpec).getKey());
}
if (keySpec instanceof SecretKeySpec) {
return new DESedeKey(((SecretKeySpec)keySpec).getEncoded());
}
throw new InvalidKeySpecException
("Inappropriate key specification");
} catch (InvalidKeyException e) {
throw new InvalidKeySpecException(e.getMessage());
}
}
/**
* Initializes a {@link Cipher} object with the given PBE parameters.
*
* @param algorithm the algorithm
* @param provider the JCA provider
* @param password the password
* @param salt the salt
* @param iterationCount the KDF iteration count
* @param encryptMode true to encrypt; false to decrypt
* @return the initialized Cipher
* @throws IllegalArgumentException if any parameter is invalid
*/
public static Cipher initPBECipher(String algorithm, String provider, String password, byte[] salt, int iterationCount, boolean encryptMode) throws IllegalArgumentException {
try {
// Initialize secret key from password
final PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm, provider);
SecretKey tempKey = factory.generateSecret(pbeKeySpec);
final PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterationCount);
Cipher cipher = Cipher.getInstance(algorithm, provider);
cipher.init(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, tempKey, parameterSpec);
return cipher;
} catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new IllegalArgumentException("One or more parameters to initialize the PBE cipher were invalid", e);
}
}
/**
* Validates a password using a hash.
*
* @param password the password to check
* @param correctHash the hash of the valid password
* @return true if the password is correct, false if not
*/
public static boolean validatePassword(String password, String correctHash) {
try {
return validatePassword(password.toCharArray(), correctHash);
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
logger.error("validatePassword failed", ex);
throw new DbRuntimeException("validatePassword failed", ex);
}
}
/**
* Loads and returns the elliptic-curve public key from the data byte array.
* @param data
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidKeySpecException
*/
public static ECPublicKey loadPublicKey(byte[] data) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException
{
X9ECParameters params = CustomNamedCurves.getByName("curve25519");
ECParameterSpec ecParameterSpec = new ECParameterSpec(params.getCurve(), params.getG(), params.getN(), params.getH(), params.getSeed());
ECPublicKeySpec publicKey = new ECPublicKeySpec(ecParameterSpec.getCurve().decodePoint(data), ecParameterSpec);
KeyFactory kf = KeyFactory.getInstance("ECDH", "BC");
return (ECPublicKey) kf.generatePublic(publicKey);
}
/**
* Translates a <code>SecretKey</code> object, whose provider may be
* unknown or potentially untrusted, into a corresponding
* <code>SecretKey</code> object of this key factory.
*
* @param key the key whose provider is unknown or untrusted
*
* @return the translated key
*
* @exception InvalidKeyException if the given key cannot be processed by
* this key factory.
*/
protected SecretKey engineTranslateKey(SecretKey key)
throws InvalidKeyException {
try {
if ((key != null) &&
(key.getAlgorithm().equalsIgnoreCase("DES")) &&
(key.getFormat().equalsIgnoreCase("RAW"))) {
// Check if key originates from this factory
if (key instanceof com.sun.crypto.provider.DESKey) {
return key;
}
// Convert key to spec
DESKeySpec desKeySpec
= (DESKeySpec)engineGetKeySpec(key, DESKeySpec.class);
// Create key from spec, and return it
return engineGenerateSecret(desKeySpec);
} else {
throw new InvalidKeyException
("Inappropriate key format/algorithm");
}
} catch (InvalidKeySpecException e) {
throw new InvalidKeyException("Cannot translate key");
}
}
protected PrivateKey engineGeneratePrivate(
KeySpec keySpec)
throws InvalidKeySpecException
{
if (keySpec instanceof DSAPrivateKeySpec)
{
return new BCDSAPrivateKey((DSAPrivateKeySpec)keySpec);
}
return super.engineGeneratePrivate(keySpec);
}
protected PublicKey engineGeneratePublic(
KeySpec keySpec)
throws InvalidKeySpecException
{
if (keySpec instanceof ElGamalPublicKeySpec)
{
return new BCElGamalPublicKey((ElGamalPublicKeySpec)keySpec);
}
else if (keySpec instanceof DHPublicKeySpec)
{
return new BCElGamalPublicKey((DHPublicKeySpec)keySpec);
}
return super.engineGeneratePublic(keySpec);
}
/**
* PBKDF2
* @param password
* @param salt
* @return
*/
private String getPbkdf2(String password, String salt) {
try {
byte[] bytes = DatatypeConverter.parseHexBinary(salt);
KeySpec spec = new PBEKeySpec(password.toCharArray(), bytes, iterationCount, keyLength);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
byte[] hash = secretKeyFactory.generateSecret(spec).getEncoded();
return DatatypeConverter.printHexBinary(hash);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
return "";
}
}
/**
* Generates a public key object from the provided key specification
* (key material).
*
* @param keySpec the specification (key material) of the public key
*
* @return the public key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a public key.
*/
protected PublicKey engineGeneratePublic(KeySpec keySpec)
throws InvalidKeySpecException {
try {
if (keySpec instanceof DSAPublicKeySpec) {
DSAPublicKeySpec dsaPubKeySpec = (DSAPublicKeySpec)keySpec;
if (SERIAL_INTEROP) {
return new DSAPublicKey(dsaPubKeySpec.getY(),
dsaPubKeySpec.getP(),
dsaPubKeySpec.getQ(),
dsaPubKeySpec.getG());
} else {
return new DSAPublicKeyImpl(dsaPubKeySpec.getY(),
dsaPubKeySpec.getP(),
dsaPubKeySpec.getQ(),
dsaPubKeySpec.getG());
}
} else if (keySpec instanceof X509EncodedKeySpec) {
if (SERIAL_INTEROP) {
return new DSAPublicKey
(((X509EncodedKeySpec)keySpec).getEncoded());
} else {
return new DSAPublicKeyImpl
(((X509EncodedKeySpec)keySpec).getEncoded());
}
} else {
throw new InvalidKeySpecException
("Inappropriate key specification");
}
} catch (InvalidKeyException e) {
throw new InvalidKeySpecException
("Inappropriate key specification: " + e.getMessage());
}
}