本文整理汇总了Java中java.security.spec.InvalidKeySpecException类的典型用法代码示例。如果您正苦于以下问题:Java InvalidKeySpecException类的具体用法?Java InvalidKeySpecException怎么用?Java InvalidKeySpecException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
InvalidKeySpecException类属于java.security.spec包,在下文中一共展示了InvalidKeySpecException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createKeyManagerFactory
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
private static KeyManagerFactory createKeyManagerFactory(
final String clientCertificateFileName, final String clientKeyFileName, final String clientKeyPassword)
throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException
{
// Creates a key manager factory
// Load and create the client certificate
final X509Certificate clientCertificate = createX509CertificateFromFile(clientCertificateFileName);
// Load the private client key
final PrivateKey privateKey = createPrivateKeyFromPemFile(clientKeyFileName);
// Client key and certificate are sent to server
final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("certificate", clientCertificate);
keyStore.setKeyEntry("private-key", privateKey,
clientKeyPassword.toCharArray(),
new Certificate[] { clientCertificate });
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, clientKeyPassword.toCharArray());
return keyManagerFactory;
}
开发者ID:PacktPublishing,项目名称:MQTT-Essentials-A-Lightweight-IoT-Protocol,代码行数:22,代码来源:SecurityHelper.java
示例2: translateSpoiledKey
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
/**
* The test case scenario implemented in the method: - create my own secret
* Key2 as an instance of a class implements PBEKey - spoil the key (set
* iteration count to 0, for example) - try to translate key -
* InvalidKeyException is expected.
*
* @return true if InvalidKeyException occurred; false - otherwise.
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public boolean translateSpoiledKey() throws NoSuchAlgorithmException,
InvalidKeySpecException {
// derive the key
SecretKey key1 = getMyOwnSecretKey();
// spoil the key
((MyPBKDF2SecretKey) key1).spoil();
// translate key
SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
try {
SecretKey key2 = skf.translateKey(key1);
} catch (InvalidKeyException ike) {
// this is expected
return true;
}
return false;
}
示例3: loadPrivateKey
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
/**
* Load a private key from a base64 encoded string
* @param key The base64 encoded key
* @return The private key
*/
public static PrivateKey loadPrivateKey(String key) {
KeyFactory kf = getKeyFactory();
if(kf == null) {
return null;
}
byte[] rawKey = Base64.decode(key, Base64.DEFAULT);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(rawKey);
try {
return kf.generatePrivate(ks);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
示例4: decodePublicKey
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
/**
* Create a new PublicKey from encoded X.509 data
*/
public static PublicKey decodePublicKey(byte[] encodedKey)
{
try
{
EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
KeyFactory keyfactory = KeyFactory.getInstance("RSA");
return keyfactory.generatePublic(encodedkeyspec);
}
catch (NoSuchAlgorithmException var3)
{
;
}
catch (InvalidKeySpecException var4)
{
;
}
LOGGER.error("Public key reconstitute failed!");
return null;
}
示例5: onEnable
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
@Override
public void onEnable() {
instance = this;
try {
mojangPublicKey = KeyFactory.getInstance("EC").generatePublic(
new X509EncodedKeySpec(Base64
.getDecoder()
.decode("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V")
)
);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
networkManager = new NetworkManager();
}
示例6: verify
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
/**
*
* if has performance problem ,change Signature to ThreadLocal instance
* @param publicKey public key after base64 encode
* @param sign 签名
* @param content original content
* @return verify result
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws InvalidKeyException
* @throws SignatureException
*/
public static boolean verify(String publicKey, String sign, String content)
throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
if (null == kf) {
throw new NoSuchAlgorithmException(RSA_ALG + " KeyFactory not available");
}
byte[] bytes = decoder.decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
PublicKey pubKey = kf.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGN_ALG);
signature.initVerify(pubKey);
signature.update(content.getBytes());
return signature.verify(decoder.decode(sign));
}
示例7: testRSAAuthenticationToken
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
@Test
public void testRSAAuthenticationToken()
throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {
String tokenstr =
"[email protected][email protected]@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwg[email protected]WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=";
RSAAuthenticationToken token = RSAAuthenticationToken.fromStr(tokenstr);
String contents = token.plainToken();
Assert.assertEquals(
"[email protected][email protected]@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ",
contents);
String sign = token.getSign();
Assert.assertEquals(
"WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=",
sign);
String pubKey =
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxKl5TNUTec7fL2degQcCk6vKf3c0wsfNK5V6elKzjWxm0MwbRj/UeR20VSnicBmVIOWrBS9LiERPPvjmmWUOSS2vxwr5XfhBhZ07gCAUNxBOTzgMo5nE45DhhZu5Jzt5qSV6o10Kq7+fCCBlDZ1UoWxZceHkUt5AxcrhEDulFjQIDAQAB";
Assert.assertTrue(RSAUtils.verify(pubKey, sign, contents));
}
示例8: createPublicKey
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
/**
* 从hex string生成公钥
*
* @param stringN
* @param stringE
* @return 构造好的公钥
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey createPublicKey(String stringN, String stringE)
throws NoSuchAlgorithmException, InvalidKeySpecException {
try {
BigInteger N = new BigInteger(stringN, 16); // hex base
BigInteger E = new BigInteger(stringE, 16); // hex base
RSAPublicKeySpec spec = new RSAPublicKeySpec(N, E);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
示例9: createKeyPairFromEncodedKeys
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
/**
* Convert encoded private and public keys (bytes) to Private / PublicKey
* interfaces and generate a KeyPair from them in order to construct a
* Wallet object in the signIn method<br>
* <b>Two different encoding</b>
*
* @param publicKeyBytes the public key with encoding X509
* @param privateKeyBytes the private key with encoding PKCS8
* @return the key pair
*/
public static KeyPair createKeyPairFromEncodedKeys(byte[] publicKeyBytes, byte[] privateKeyBytes) {
// Generate specs
final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
try {
// Create PublicKey and PrivateKey interfaces using the factory
final PrivateKey privateKey = dsaKeyFactory.generatePrivate(privateKeySpec);
final PublicKey publicKey = dsaKeyFactory.generatePublic(publicKeySpec);
return new KeyPair(publicKey, privateKey);
} catch (InvalidKeySpecException ex) {
logAndAbort("Unable to create key pair. Abort!", ex);
}
return null;
}
示例10: rsaSign
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
public static String rsaSign(String content, String privateKey,
String charset) throws AlipayApiException {
try {
PrivateKey priKey = getPrivateKeyFromPKCS8(AlipayConstants.SIGN_TYPE_RSA,
new ByteArrayInputStream(privateKey.getBytes()));
java.security.Signature signature = java.security.Signature
.getInstance(AlipayConstants.SIGN_ALGORITHMS);
signature.initSign(priKey);
if (StringUtils.isEmpty(charset)) {
signature.update(content.getBytes());
} else {
signature.update(content.getBytes(charset));
}
byte[] signed = signature.sign();
return new String(Base64.encodeBase64(signed));
} catch (InvalidKeySpecException ie) {
throw new AlipayApiException("RSA私钥格式不正确,请检查是否正确配置了PKCS8格式的私钥", ie);
} catch (Exception e) {
throw new AlipayApiException("RSAcontent = " + content + "; charset = " + charset, e);
}
}
示例11: CBCEncrypt
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
public static String CBCEncrypt(int alg, int KeySize, String inFile, String pwd, String mode) throws NoSuchAlgorithmException, InvalidKeySpecException, DataLengthException, IllegalStateException, InvalidCipherTextException, IOException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException
{
String res = "";
byte[] plain = loadFile(inFile);
Encryptor enc = new Encryptor();
enc.setParameters(KeySize, alg);
enc.setEncParameters(alg, pwd, KeySize, mode);
byte[] bytesRes = enc.CBCEncrypt(plain, alg);
save2File(inFile + ".enc", bytesRes);
res = "Done! file contents encrypted and saved to a corresponding enc file!";
return res;
}
示例12: engineGenerateSecret
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
/**
* 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 DESKeySpec) {
return new DESKey(((DESKeySpec)keySpec).getKey());
}
if (keySpec instanceof SecretKeySpec) {
return new DESKey(((SecretKeySpec)keySpec).getEncoded());
}
throw new InvalidKeySpecException(
"Inappropriate key specification");
} catch (InvalidKeyException e) {
throw new InvalidKeySpecException(e.getMessage());
}
}
示例13: main
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
// TODO This code is demo as the passphrase is hardcoded.
SystemInfo info = new SystemInfo();
String salt = info.getHardware().getProcessor().getProcessorID() + info.getOperatingSystem().getFileSystem().getFileStores()[0].getUUID();
String passPhrase = "Rudy";
// PBKDF2WithHmacSHA1 available on Java 7 and Java 8. Must match value used on LocalSecretFactory.
// TODO possible usage scenario. using theis local secret, the end user can create the OfflineToken with a Web application (where he needs to authenticate himself
// in order to create a correct OfflineToken instance for the user.
byte[] secret = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(
new PBEKeySpec(passPhrase.toCharArray(), salt.getBytes(), 1024, 256)).getEncoded();
String secret64 = Base64Codec.encodeToString(secret, true);
System.out.println("Local secret value is " + secret64);
}
示例14: validatePassword
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
/**
* 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(char[] password, String correctHash)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
// Decode the hash into its parameters
String[] params = correctHash.split(":");
int iterations = Integer.parseInt(params[ITERATION_INDEX]);
byte[] salt = fromHex(params[SALT_INDEX]);
byte[] hash = fromHex(params[PBKDF2_INDEX]);
// Compute the hash of the provided password, using the same salt,
// iteration count, and hash length
byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
// Compare the hashes in constant time. The password is correct if
// both hashes match.
return slowEquals(hash, testHash);
}
示例15: hash
import java.security.spec.InvalidKeySpecException; //导入依赖的package包/类
/**
* This method will hash the password and salt combination. Be careful, this method will erase the password after hashed it.
* You must be sure that you do not need it after using this method.
*
* @param password the password who needs to be hashed
* @param salt some list of <code>byte</code> which will be included in the password
* @return a hash of the password and salting combination.
*/
public static byte[] hash(char[] password, byte[] salt) {
final PBEKeySpec spec = new PBEKeySpec(password, salt, SecurityUtils.ITERATIONS, SecurityUtils.KEY_LENGTH);
try {
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SecurityUtils.ALGORITHM);
SecretKey key = secretKeyFactory.generateSecret(spec);
return key.getEncoded();
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
LOGGER.debug(e.getMessage(), e);
throw new SecurityException(e);
} finally {
// erase the password in the char array in order to not retrieve it in the java memory
spec.clearPassword();
}
}