本文整理汇总了Java中java.security.InvalidKeyException类的典型用法代码示例。如果您正苦于以下问题:Java InvalidKeyException类的具体用法?Java InvalidKeyException怎么用?Java InvalidKeyException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
InvalidKeyException类属于java.security包,在下文中一共展示了InvalidKeyException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: generateSignatureBlock
import java.security.InvalidKeyException; //导入依赖的package包/类
private static byte[] generateSignatureBlock(
SignerConfig signerConfig, byte[] signatureFileBytes)
throws InvalidKeyException, CertificateEncodingException, SignatureException {
JcaCertStore certs = new JcaCertStore(signerConfig.certificates);
X509Certificate signerCert = signerConfig.certificates.get(0);
String jcaSignatureAlgorithm =
getJcaSignatureAlgorithm(
signerCert.getPublicKey(), signerConfig.signatureDigestAlgorithm);
try {
ContentSigner signer =
new JcaContentSignerBuilder(jcaSignatureAlgorithm)
.build(signerConfig.privateKey);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
gen.addSignerInfoGenerator(
new SignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().build(),
SignerInfoSignatureAlgorithmFinder.INSTANCE)
.setDirectSignature(true)
.build(signer, new JcaX509CertificateHolder(signerCert)));
gen.addCertificates(certs);
CMSSignedData sigData =
gen.generate(new CMSProcessableByteArray(signatureFileBytes), false);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {
DEROutputStream dos = new DEROutputStream(out);
dos.writeObject(asn1.readObject());
}
return out.toByteArray();
} catch (OperatorCreationException | CMSException | IOException e) {
throw new SignatureException("Failed to generate signature", e);
}
}
示例2: encrypt
import java.security.InvalidKeyException; //导入依赖的package包/类
public static String encrypt(String str) {
if (str == null) return null;
Cipher cipher;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec,
new IvParameterSpec(ips.getBytes("UTF-8")));
byte[] encrypted = cipher.doFinal(str.getBytes("UTF-8"));
String Str = new String(Base64.encodeBase64(encrypted));
return Str;
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| InvalidKeyException | InvalidAlgorithmParameterException
| IllegalBlockSizeException | BadPaddingException
| UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
示例3: constructKey
import java.security.InvalidKeyException; //导入依赖的package包/类
static final Key constructKey(byte[] encoding, String keyAlgorithm,
int keyType)
throws InvalidKeyException, NoSuchAlgorithmException {
Key result = null;
switch (keyType) {
case Cipher.SECRET_KEY:
result = ConstructKeys.constructSecretKey(encoding,
keyAlgorithm);
break;
case Cipher.PRIVATE_KEY:
result = ConstructKeys.constructPrivateKey(encoding,
keyAlgorithm);
break;
case Cipher.PUBLIC_KEY:
result = ConstructKeys.constructPublicKey(encoding,
keyAlgorithm);
break;
}
return result;
}
示例4: verify
import java.security.InvalidKeyException; //导入依赖的package包/类
@Override
public boolean verify(final RsaSha256Condition condition, final byte[] message) {
Objects.requireNonNull(condition,
"Can't verify a RsaSha256Fulfillment against an null condition.");
Objects.requireNonNull(message, "Message must not be null!");
if (!getCondition().equals(condition)) {
return false;
}
try {
Signature rsaSigner = Signature.getInstance(SHA_256_WITH_RSA_PSS);
rsaSigner.initVerify(publicKey);
rsaSigner.update(message);
return rsaSigner.verify(signature);
} catch (InvalidKeyException | NoSuchAlgorithmException | SignatureException e) {
throw new RuntimeException(e);
}
}
示例5: init
import java.security.InvalidKeyException; //导入依赖的package包/类
void init(boolean decrypting, String algorithm, byte[] key)
throws InvalidKeyException {
if (!algorithm.equalsIgnoreCase("AES")
&& !algorithm.equalsIgnoreCase("Rijndael")) {
throw new InvalidKeyException
("Wrong algorithm: AES or Rijndael required");
}
if (!isKeySizeValid(key.length)) {
throw new InvalidKeyException("Invalid AES key length: " +
key.length + " bytes");
}
if (!Arrays.equals(key, lastKey)) {
// re-generate session key 'sessionK' when cipher key changes
makeSessionKey(key);
lastKey = key.clone(); // save cipher key
}
// set sub key to the corresponding session Key
this.K = (int[]) sessionK[(decrypting? 1:0)];
}
示例6: processIniciatorState1
import java.security.InvalidKeyException; //导入依赖的package包/类
private void processIniciatorState1(int accountId, int peerId, @NonNull KeyExchangeSession session, @NonNull ExchangeMessage message) {
String hisAesKey = message.getAesKey();
PrivateKey myPrivateKey = session.getMyPrivateKey();
try {
byte[] hisAesEncoded = Base64.decode(hisAesKey, Base64.DEFAULT);
String hisOriginalAes = CryptHelper.decryptRsa(hisAesEncoded, myPrivateKey);
session.setHisAesKey(hisOriginalAes);
String myOriginalAesKey = CryptHelper.generateRandomAesKey(Version.ofCurrent().getAesKeySize());
session.setMyAesKey(myOriginalAesKey);
PublicKey hisPublicKey = CryptHelper.createRsaPublicKeyFromString(message.getPublicKey());
byte[] myEncodedAesKey = CryptHelper.encryptRsa(myOriginalAesKey, hisPublicKey);
String myEncodedAesKeyBase64 = Base64.encodeToString(myEncodedAesKey, Base64.DEFAULT);
Logger.d(TAG, "processIniciatorState1, myOriginalAesKey: " + myOriginalAesKey + ", hisOriginalAes: " + hisOriginalAes);
ExchangeMessage m = new ExchangeMessage.Builder(Version.CURRENT, session.getId(), SessionState.INITIATOR_STATE_2)
.setAesKey(myEncodedAesKeyBase64)
.create();
sendMessage(accountId, peerId, m);
} catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeySpecException e) {
e.printStackTrace();
}
}
示例7: testRSAAuthenticationToken
import java.security.InvalidKeyException; //导入依赖的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: addKeyAgreementRecipients
import java.security.InvalidKeyException; //导入依赖的package包/类
/**
* Add multiple key agreement based recipients (sharing a single KeyAgreeRecipientInfo structure).
*
* @deprecated use the addRecipientGenerator and JceKeyAgreeRecipientInfoGenerator
* @param agreementAlgorithm key agreement algorithm to use.
* @param senderPrivateKey private key to initialise sender side of agreement with.
* @param senderPublicKey sender public key to include with message.
* @param recipientCerts recipients' public key certificates.
* @param cekWrapAlgorithm OID for key wrapping algorithm to use.
* @param provider provider to use for the agreement calculation.
* @exception NoSuchAlgorithmException if the algorithm requested cannot be found
* @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
*/
public void addKeyAgreementRecipients(
String agreementAlgorithm,
PrivateKey senderPrivateKey,
PublicKey senderPublicKey,
Collection recipientCerts,
String cekWrapAlgorithm,
Provider provider)
throws NoSuchAlgorithmException, InvalidKeyException
{
JceKeyAgreeRecipientInfoGenerator recipientInfoGenerator = new JceKeyAgreeRecipientInfoGenerator(new ASN1ObjectIdentifier(agreementAlgorithm), senderPrivateKey, senderPublicKey, new ASN1ObjectIdentifier(cekWrapAlgorithm)).setProvider(provider);
for (Iterator it = recipientCerts.iterator(); it.hasNext();)
{
try
{
recipientInfoGenerator.addRecipient((X509Certificate)it.next());
}
catch (CertificateEncodingException e)
{
throw new IllegalArgumentException("unable to encode certificate: " + e.getMessage());
}
}
oldRecipientInfoGenerators.add(recipientInfoGenerator);
}
示例9: getSuggestedSignatureAlgorithms
import java.security.InvalidKeyException; //导入依赖的package包/类
/**
* Gets the APK Signature Scheme v2 signature algorithms to be used for signing an APK using the
* provided key.
*
* @param minSdkVersion minimum API Level of the platform on which the APK may be installed (see
* AndroidManifest.xml minSdkVersion attribute).
*
* @throws InvalidKeyException if the provided key is not suitable for signing APKs using
* APK Signature Scheme v2
*/
public static List<SignatureAlgorithm> getSuggestedSignatureAlgorithms(
PublicKey signingKey, int minSdkVersion) throws InvalidKeyException {
String keyAlgorithm = signingKey.getAlgorithm();
if ("RSA".equalsIgnoreCase(keyAlgorithm)) {
// Use RSASSA-PKCS1-v1_5 signature scheme instead of RSASSA-PSS to guarantee
// deterministic signatures which make life easier for OTA updates (fewer files
// changed when deterministic signature schemes are used).
// Pick a digest which is no weaker than the key.
int modulusLengthBits = ((RSAKey) signingKey).getModulus().bitLength();
if (modulusLengthBits <= 3072) {
// 3072-bit RSA is roughly 128-bit strong, meaning SHA-256 is a good fit.
return Collections.singletonList(SignatureAlgorithm.RSA_PKCS1_V1_5_WITH_SHA256);
} else {
// Keys longer than 3072 bit need to be paired with a stronger digest to avoid the
// digest being the weak link. SHA-512 is the next strongest supported digest.
return Collections.singletonList(SignatureAlgorithm.RSA_PKCS1_V1_5_WITH_SHA512);
}
} else if ("DSA".equalsIgnoreCase(keyAlgorithm)) {
// DSA is supported only with SHA-256.
return Collections.singletonList(SignatureAlgorithm.DSA_WITH_SHA256);
} else if ("EC".equalsIgnoreCase(keyAlgorithm)) {
// Pick a digest which is no weaker than the key.
int keySizeBits = ((ECKey) signingKey).getParams().getOrder().bitLength();
if (keySizeBits <= 256) {
// 256-bit Elliptic Curve is roughly 128-bit strong, meaning SHA-256 is a good fit.
return Collections.singletonList(SignatureAlgorithm.ECDSA_WITH_SHA256);
} else {
// Keys longer than 256 bit need to be paired with a stronger digest to avoid the
// digest being the weak link. SHA-512 is the next strongest supported digest.
return Collections.singletonList(SignatureAlgorithm.ECDSA_WITH_SHA512);
}
} else {
throw new InvalidKeyException("Unsupported key algorithm: " + keyAlgorithm);
}
}
示例10: DSAPrivateKey
import java.security.InvalidKeyException; //导入依赖的package包/类
/**
* Make a DSA private key out of a private key and three parameters.
*/
public DSAPrivateKey(BigInteger x, BigInteger p,
BigInteger q, BigInteger g)
throws InvalidKeyException {
this.x = x;
algid = new AlgIdDSA(p, q, g);
try {
key = new DerValue(DerValue.tag_Integer,
x.toByteArray()).toByteArray();
encode();
} catch (IOException e) {
InvalidKeyException ike = new InvalidKeyException(
"could not DER encode x: " + e.getMessage());
ike.initCause(e);
throw ike;
}
}
示例11: AttachmentCipherOutputStream
import java.security.InvalidKeyException; //导入依赖的package包/类
public AttachmentCipherOutputStream(byte[] combinedKeyMaterial,
OutputStream outputStream)
throws IOException
{
try {
this.outputStream = outputStream;
this.cipher = initializeCipher();
this.mac = initializeMac();
this.messageDigest = MessageDigest.getInstance("SHA256");
byte[][] keyParts = Util.split(combinedKeyMaterial, 32, 32);
this.cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyParts[0], "AES"));
this.mac.init(new SecretKeySpec(keyParts[1], "HmacSHA256"));
mac.update(cipher.getIV());
messageDigest.update(cipher.getIV());
outputStream.write(cipher.getIV());
ciphertextLength += cipher.getIV().length;
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
示例12: decrypt
import java.security.InvalidKeyException; //导入依赖的package包/类
public static String decrypt(String str) {
if (str == null) return null;
Cipher cipher;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec,
new IvParameterSpec(ips.getBytes("UTF-8")));
byte[] byteStr = Base64.decodeBase64(str.getBytes());
String Str = new String(cipher.doFinal(byteStr), "UTF-8");
return Str;
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| InvalidKeyException | InvalidAlgorithmParameterException
| IllegalBlockSizeException | BadPaddingException
| UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
示例13: getInstance
import java.security.InvalidKeyException; //导入依赖的package包/类
public static MeviusTransferPacket getInstance(PublicKey publickey, MeviusPacket packet)
throws MeviusCipherException {
try {
DESedeKeySpec desKeySpec = new DESedeKeySpec(((String) MeviusCipherKey.randomDESKey().getKey()).getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
Key key = keyFactory.generateSecret(desKeySpec);
Cipher c = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "SunJCE");
c.init(Cipher.ENCRYPT_MODE, publickey);
byte[] bkey = convertObj(key, c);
c = Cipher.getInstance("DESede/ECB/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, key);
byte[] bobj = convertObj(packet, c);
return new MeviusTransferPacket(bkey, bobj);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException
| IOException | InvalidKeySpecException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
throw new MeviusCipherException(e.getLocalizedMessage());
}
}
示例14: engineWrap
import java.security.InvalidKeyException; //导入依赖的package包/类
/**
* Wrap a key.
*
* @param key the key to be wrapped.
*
* @return the wrapped key.
*
* @exception IllegalBlockSizeException if this cipher is a block
* cipher, no padding has been requested, and the length of the
* encoding of the key to be wrapped is not a
* multiple of the block size.
*
* @exception InvalidKeyException if it is impossible or unsafe to
* wrap the key with this cipher (e.g., a hardware protected key is
* being passed to a software only cipher).
*/
protected final byte[] engineWrap(Key key)
throws IllegalBlockSizeException, InvalidKeyException
{
byte[] result = null;
try {
byte[] encodedKey = key.getEncoded();
if ((encodedKey == null) || (encodedKey.length == 0)) {
throw new InvalidKeyException("Cannot get an encoding of " +
"the key to be wrapped");
}
result = engineDoFinal(encodedKey, 0, encodedKey.length);
} catch (BadPaddingException e) {
// Should never happen
}
return result;
}
示例15: equals
import java.security.InvalidKeyException; //导入依赖的package包/类
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Key == false) {
return false;
}
try {
byte[] thisEncoded = this.getEncodedInternal();
byte[] otherEncoded;
if (obj instanceof X509Key) {
otherEncoded = ((X509Key)obj).getEncodedInternal();
} else {
otherEncoded = ((Key)obj).getEncoded();
}
return Arrays.equals(thisEncoded, otherEncoded);
} catch (InvalidKeyException e) {
return false;
}
}