Java 类java.security.InvalidKeyException 实例源码

项目:walle    文件:V1SchemeSigner.java   
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);
    }
}
项目:quilt    文件:RsaSha256Fulfillment.java   
@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);
  }
}
项目:Daejeon-People    文件:AES.java   
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;
}
项目:OpenJSharp    文件:AESCrypt.java   
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)];
}
项目:Phoenix-for-VK    文件:KeyExchangeService.java   
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();
    }
}
项目:ipack    文件:CMSEnvelopedGenerator.java   
/**
 * 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);
}
项目:jdk8u-jdk    文件:ConstructKeys.java   
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;
}
项目:FApkSigner    文件:V2SchemeSigner.java   
/**
 * 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);
    }
}
项目:openjdk-jdk10    文件:DSAPrivateKey.java   
/**
 * 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;
    }
}
项目:PeSanKita-lib    文件:AttachmentCipherOutputStream.java   
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);
  }
}
项目:DMS    文件:AES256.java   
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;
}
项目:Mevius-IO    文件:MeviusTransferPacket.java   
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());
    }
}
项目:openjdk-jdk10    文件:CipherWithWrappingSpi.java   
/**
 * 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;
}
项目:jdk8u-jdk    文件:X509Key.java   
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;
    }
}
项目:openjdk-jdk10    文件:TestAESOids.java   
public static void main(String[] args) throws Exception {
    for (DataTuple dataTuple : DATA) {
        int maxAllowedKeyLength =
                getMaxAllowedKeyLength(dataTuple.algorithm);
        boolean supportedKeyLength =
                maxAllowedKeyLength >= dataTuple.keyLength;

        try {
            runTest(dataTuple, supportedKeyLength);
            System.out.println("passed");
        } catch (InvalidKeyException ike) {
            if (supportedKeyLength) {
                throw new RuntimeException(String.format(
                        "The key length %d is supported, but test failed.",
                        dataTuple.keyLength), ike);
            } else {
                System.out.printf(
                        "Catch expected InvalidKeyException due "
                                + "to the key length %d is greater than "
                                + "max supported key length %d%n",
                        dataTuple.keyLength, maxAllowedKeyLength);
            }
        }
    }
}
项目:jdk8u-jdk    文件:SignatureDSA.java   
/**
 * @inheritDoc
 */
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
    if (!(privateKey instanceof PrivateKey)) {
        String supplied = privateKey.getClass().getName();
        String needed = PrivateKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
    size = ((DSAKey)privateKey).getParams().getQ().bitLength();
}
项目:dracoon-dropzone    文件:CryptoUtil.java   
private byte[] decrypt(byte[] cipherText, byte[] key, byte[] initialVector)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    Cipher cipher = Cipher.getInstance(cipherTransformation);
    SecretKeySpec secretKeySpecy = new SecretKeySpec(key, aesEncryptionAlgorithm);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec);
    cipherText = cipher.doFinal(cipherText);
    return cipherText;
}
项目:ipack    文件:SignatureSpi.java   
protected void engineInitVerify(
    PublicKey   publicKey)
    throws InvalidKeyException
{
    CipherParameters    param;

    if (publicKey instanceof ECPublicKey)
    {
        param = ECUtil.generatePublicKeyParameter(publicKey);
    }
    else if (publicKey instanceof GOST3410Key)
    {
        param = GOST3410Util.generatePublicKeyParameter(publicKey);
    }
    else
    {
        try
        {
            byte[]  bytes = publicKey.getEncoded();

            publicKey = BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(bytes));

            if (publicKey instanceof ECPublicKey)
            {
                param = ECUtil.generatePublicKeyParameter(publicKey);
            }
            else
            {
                throw new InvalidKeyException("can't recognise key type in DSA based signer");
            }
        }
        catch (Exception e)
        {
            throw new InvalidKeyException("can't recognise key type in DSA based signer");
        }
    }

    digest.reset();
    signer.init(false, param);
}
项目:openjdk-jdk10    文件:PBKDF2HmacSHA1Factory.java   
/**
 * 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 {
    if ((key != null) &&
        (key.getAlgorithm().equalsIgnoreCase("PBKDF2WithHmacSHA1")) &&
        (key.getFormat().equalsIgnoreCase("RAW"))) {

        // Check if key originates from this factory
        if (key instanceof com.sun.crypto.provider.PBKDF2KeyImpl) {
            return key;
        }
        // Check if key implements the PBEKey
        if (key instanceof javax.crypto.interfaces.PBEKey) {
            javax.crypto.interfaces.PBEKey pKey =
                (javax.crypto.interfaces.PBEKey) key;
            try {
                PBEKeySpec spec =
                    new PBEKeySpec(pKey.getPassword(),
                                   pKey.getSalt(),
                                   pKey.getIterationCount(),
                                   pKey.getEncoded().length*8);
                return new PBKDF2KeyImpl(spec, "HmacSHA1");
            } catch (InvalidKeySpecException re) {
                InvalidKeyException ike = new InvalidKeyException
                    ("Invalid key component(s)");
                ike.initCause(re);
                throw ike;
            }
        }
    }
    throw new InvalidKeyException("Invalid key format/algorithm");
}
项目:keepass2android    文件:JCEStreamCipher.java   
protected void engineInit(
    int                 opmode,
    Key                 key,
    SecureRandom        random) 
    throws InvalidKeyException
{
    try
    {
        engineInit(opmode, key, (AlgorithmParameterSpec)null, random);
    }
    catch (InvalidAlgorithmParameterException e)
    {
        throw new InvalidKeyException(e.getMessage());
    }
}
项目:ipack    文件:SignedPublicKeyAndChallenge.java   
public boolean verify(String provider)
    throws NoSuchAlgorithmException, SignatureException, 
           NoSuchProviderException, InvalidKeyException
{
    Signature sig = null;
    if (provider == null)
    {
        sig = Signature.getInstance(signatureAlgorithm.getAlgorithm().getId());
    }
    else
    {
        sig = Signature.getInstance(signatureAlgorithm.getAlgorithm().getId(), provider);
    }
    PublicKey pubKey = this.getPublicKey(provider);
    sig.initVerify(pubKey);
    try
    {
        DERBitString pkBytes = new DERBitString(pkac);
        sig.update(pkBytes.getBytes());

        return sig.verify(signature.getBytes());
    }
    catch (Exception e)
    {
        throw new InvalidKeyException("error encoding public key");
    }
}
项目:ipack    文件:CMSSignedDataStreamGenerator.java   
/**
 * @deprecated use addSignedInfoGenerator
 */
public void addSigner(
    PrivateKey                  key,
    X509Certificate             cert,
    String                      encryptionOID,
    String                      digestOID,
    CMSAttributeTableGenerator  signedAttrGenerator,
    CMSAttributeTableGenerator  unsignedAttrGenerator,
    Provider                    sigProvider)
    throws NoSuchAlgorithmException, InvalidKeyException
{
    addSigner(key, cert, encryptionOID, digestOID, signedAttrGenerator, unsignedAttrGenerator, sigProvider, sigProvider);
}
项目:openjdk-jdk10    文件:LargeByteBufferTest.java   
@Override
public void doTest(String alg) throws NoSuchAlgorithmException,
        InvalidKeyException, NoSuchProviderException {
    SecretKey key = Utils.getSecretKeySpec();

    // instantiate Mac object and init it with a SecretKey
    Mac mac = Mac.getInstance(alg, "SunJCE");
    mac.init(key);

    // prepare buffer
    byte[] data = new byte[BUFFER_SIZE];
    for (int i = 0; i < BUFFER_SIZE; i++) {
        data[i] = (byte) (i % 256);
    }

    ByteBuffer buf = ByteBuffer.wrap(data);
    int limitBefore = buf.limit();

    mac.update(buf);
    mac.doFinal();

    int limitAfter = buf.limit();
    int positonAfter = buf.position();

    if (limitAfter != limitBefore) {
        System.out.println("limit after = " + limitAfter);
        System.out.println("limit before = " + limitBefore);
        throw new RuntimeException("Test failed: "
                + "limit of buffer has been chenged.");
    }

    if (positonAfter != limitAfter) {
        System.out.println("position after = " + positonAfter);
        System.out.println("limit after = " + limitAfter);
        throw new RuntimeException("Test failed: "
                + "position of buffer isn't equal to its limit");
    }
}
项目:ipack    文件:McEliecePKCSCipherSpi.java   
protected void initCipherDecrypt(Key key, AlgorithmParameterSpec params)
    throws InvalidKeyException, InvalidAlgorithmParameterException
{
    CipherParameters param;
    param = McElieceKeysToParams.generatePrivateKeyParameter((PrivateKey)key);

    digest.reset();
    cipher.init(false, param);
    this.maxPlainTextSize = cipher.maxPlainTextSize;
    this.cipherTextSize = cipher.cipherTextSize;
}
项目:rtmp-rtsp-stream-client-java    文件:Crypto.java   
/**
 * Calculates an HMAC SHA256 hash using a default key length.
 *
 *
 * @param input
 * @param key
 * @return hmac hashed bytes
 */
public byte[] calculateHmacSHA256(byte[] input, byte[] key) {
    byte[] output = null;
    try {
        hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256"));
        output = hmacSHA256.doFinal(input);
    } catch (InvalidKeyException e) {
        Log.e(TAG, "Invalid key", e);
    }
    return output;
}
项目:ipack    文件:PKCS10CertificationRequest.java   
/**
 * create a PKCS10 certfication request using the BC provider.
 */
public PKCS10CertificationRequest(
    String              signatureAlgorithm,
    X500Principal       subject,
    PublicKey           key,
    ASN1Set             attributes,
    PrivateKey          signingKey)
    throws NoSuchAlgorithmException, NoSuchProviderException,
            InvalidKeyException, SignatureException
{
    this(signatureAlgorithm, convertName(subject), key, attributes, signingKey, BouncyCastleProvider.PROVIDER_NAME);
}
项目:OpenJSharp    文件:DESKeyFactory.java   
/**
 * 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");
    }
}
项目:RISE-V2G    文件:SecurityUtils.java   
/**
 * Signs the SignedInfo element of the V2GMessage header.
 * 
 * @param signedInfoElementExi The EXI-encoded SignedInfo element given as a byte array
 * @param ecPrivateKey The private key which is used to sign the SignedInfo element
 * @return The signature value for the SignedInfo element given as a byte array
 */
public static byte[] signSignedInfoElement(byte[] signedInfoElementExi, ECPrivateKey ecPrivateKey) {
    try {
        Signature ecdsa = Signature.getInstance("SHA256withECDSA", "SunEC");

        getLogger().debug("EXI encoded SignedInfo: " + ByteUtils.toHexString(signedInfoElementExi));

        if (ecPrivateKey != null) {
            getLogger().debug("\n\tPrivate key used for creating signature: " + ByteUtils.toHexString(ecPrivateKey.getS().toByteArray()));

            ecdsa.initSign(ecPrivateKey);
            ecdsa.update(signedInfoElementExi);

            byte[] signature = ecdsa.sign();

            // Java operates on DER encoded signatures, but we must send the raw r and s values as signature 
            byte[] rawSignature = getRawSignatureFromDEREncoding(signature);

            getLogger().debug("Signature value: " + ByteUtils.toHexString(rawSignature));

            return rawSignature;
        } else {
            getLogger().error("Private key used to sign SignedInfo element is null");
            return null;
        }   
    } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) {
        getLogger().error(e.getClass().getSimpleName() + " occurred while trying to create signature", e);
        return null;
    }
}
项目:FApkSigner    文件:DefaultApkSignerEngine.java   
/**
 * Returns a new {@code DefaultApkSignerEngine} instance configured based on the
 * configuration of this builder.
 */
public DefaultApkSignerEngine build() throws InvalidKeyException {
    return new DefaultApkSignerEngine(
            mSignerConfigs,
            mMinSdkVersion,
            mV1SigningEnabled,
            mV2SigningEnabled,
            mOtherSignersSignaturesPreserved,
            mCreatedBy);
}
项目:ipack    文件:DHUtil.java   
static public AsymmetricKeyParameter generatePrivateKeyParameter(
    PrivateKey    key)
    throws InvalidKeyException
{
    if (key instanceof DHPrivateKey)
    {
        DHPrivateKey    k = (DHPrivateKey)key;

        return new DHPrivateKeyParameters(k.getX(),
            new DHParameters(k.getParams().getP(), k.getParams().getG(), null, k.getParams().getL()));
    }

    throw new InvalidKeyException("can't identify DH private key.");
}
项目:ipack    文件:BaseStreamCipher.java   
protected void engineInit(
    int                 opmode,
    Key                 key,
    SecureRandom        random) 
    throws InvalidKeyException
{
    try
    {
        engineInit(opmode, key, (AlgorithmParameterSpec)null, random);
    }
    catch (InvalidAlgorithmParameterException e)
    {
        throw new InvalidKeyException(e.getMessage());
    }
}
项目:ipack    文件:BaseBlockCipher.java   
protected void engineInit(
    int                 opmode,
    Key                 key,
    AlgorithmParameters params,
    SecureRandom        random) 
throws InvalidKeyException, InvalidAlgorithmParameterException
{
    AlgorithmParameterSpec  paramSpec = null;

    if (params != null)
    {
        for (int i = 0; i != availableSpecs.length; i++)
        {
            try
            {
                paramSpec = params.getParameterSpec(availableSpecs[i]);
                break;
            }
            catch (Exception e)
            {
                // try again if possible
            }
        }

        if (paramSpec == null)
        {
            throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString());
        }
    }

    engineInit(opmode, key, paramSpec, random);

    engineParams = params;
}
项目:OpenJSharp    文件:DSAKeyFactory.java   
/**
 * Translates a key object, whose provider may be unknown or potentially
 * untrusted, into a corresponding key 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 Key engineTranslateKey(Key key) throws InvalidKeyException {

    try {

        if (key instanceof java.security.interfaces.DSAPublicKey) {
            // Check if key originates from this factory
            if (key instanceof sun.security.provider.DSAPublicKey) {
                return key;
            }
            // Convert key to spec
            DSAPublicKeySpec dsaPubKeySpec
                = engineGetKeySpec(key, DSAPublicKeySpec.class);
            // Create key from spec, and return it
            return engineGeneratePublic(dsaPubKeySpec);

        } else if (key instanceof java.security.interfaces.DSAPrivateKey) {
            // Check if key originates from this factory
            if (key instanceof sun.security.provider.DSAPrivateKey) {
                return key;
            }
            // Convert key to spec
            DSAPrivateKeySpec dsaPrivKeySpec
                = engineGetKeySpec(key, DSAPrivateKeySpec.class);
            // Create key from spec, and return it
            return engineGeneratePrivate(dsaPrivKeySpec);

        } else {
            throw new InvalidKeyException("Wrong algorithm type");
        }

    } catch (InvalidKeySpecException e) {
        throw new InvalidKeyException("Cannot translate key: "
                                      + e.getMessage());
    }
}
项目:crypto-shuffle    文件:SymmetricEncryptionAlgorithm.java   
private static byte[] aesDecrypt(@NotNull byte[] key, @NotNull byte[] encryptedText) {
    @NotNull SecretKeySpec aesKey = new SecretKeySpec(key, "AES");
    Cipher aes = SymmetricEncryptionAlgorithmHelper.getAesCipherInstance();
    try {
        aes.init(Cipher.DECRYPT_MODE, aesKey);
        return aes.doFinal(encryptedText);
    } catch (@NotNull InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
        throw new RuntimeException("Problem with AES decrypt", e);
    }
}
项目:kafka-0.11.0.0-src-with-comment    文件:ScramSaslClient.java   
private void handleServerFinalMessage(byte[] signature) throws SaslException {
    try {
        byte[] serverKey = formatter.serverKey(saltedPassword);
        byte[] serverSignature = formatter.serverSignature(serverKey, clientFirstMessage, serverFirstMessage, clientFinalMessage);
        if (!Arrays.equals(signature, serverSignature))
            throw new SaslException("Invalid server signature in server final message");
    } catch (InvalidKeyException e) {
        throw new SaslException("Sasl server signature verification failed", e);
    }
}
项目:zipkin-azure    文件:LazyRegisterEventProcessorFactoryWithHostTest.java   
@Test
public void close_cancelsPendingRegistration() throws Exception {
  LazyRegisterEventProcessorFactoryWithHost
      lazy = new TestLazyRegisterEventProcessorFactoryWithHost() {
    @Override Future<?> registerEventProcessorFactoryWithHost() throws InvalidKeyException {
      return registration; // note: we aren't setting this done!
    }
  };

  lazy.get();
  lazy.close();

  assertThat(registration).isCancelled();
  assertThat(unregistered.get()).isTrue();
}
项目:ipack    文件:CMSSignedDataStreamGenerator.java   
/**
 * add a signer - no attributes other than the default ones will be
 * provided here.
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @deprecated use addSignedInfoGenerator
 */
public void addSigner(
    PrivateKey      key,
    byte[]          subjectKeyID,
    String          encryptionOID,
    String          digestOID,
    String          sigProvider)
    throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException
{
    addSigner(key, subjectKeyID, encryptionOID, digestOID, CMSUtils.getProvider(sigProvider));
}
项目:springboot-shiro-cas-mybatis    文件:MockX509CRL.java   
/**
 * @see java.security.cert.X509CRL#verify(java.security.PublicKey)
 */
@Override
public void verify(final PublicKey key) throws CRLException,
NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException,
SignatureException {
    // Do nothing to indicate valid signature
}
项目:playTorrent    文件:BitDecoder.java   
private void decode() throws IOException, InvalidKeyException {
    int type = this.in.read();
    if (type != 'd') {
        throw new InvalidKeyException("We expect dictionary first, but " + (char)type);
    }
    // start decode dictionary
    infoMaps = decodeDictionary(this.in);
}