微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java.security.PrivateKey的实例源码

项目:openjdk-jdk10    文件TestSignatures.java   
private static void testSignature(String algorithm,PrivateKey privateKey,PublicKey publicKey) throws Exception {
    System.out.println("Testing " + algorithm + "...");
    Signature s = Signature.getInstance(algorithm,provider);
    s.initSign(privateKey);
    s.update(data);
    byte[] sig = s.sign();
    s.initVerify(publicKey);
    s.update(data);
    boolean result;
    result = s.verify(sig);
    if (result == false) {
        throw new Exception("Verification 1 Failed");
    }
    s.update(data);
    result = s.verify(sig);
    if (result == false) {
        throw new Exception("Verification 2 Failed");
    }
    result = s.verify(sig);
    if (result == true) {
        throw new Exception("Verification 3 succeeded");
    }
}
项目:openjdk-jdk10    文件DSAKeyFactory.java   
/**
 * 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());
    }
}
项目:javaide    文件CustomKeySigner.java   
/** KeyStore-type agnostic.  This method will sign the zip file,automatically handling JKS or BKS keystores. */
public static void signZip( ZipSigner zipSigner,String keystorePath,char[] keystorePw,String certAlias,char[] certPw,String signatureAlgorithm,String inputZipFilename,String outputZipFilename)
    throws Exception
{
    zipSigner.issueLoadingCertAndKeysProgressEvent();
    KeyStore keystore = KeyStoreFileManager.loadKeyStore( keystorePath,keystorePw);
    Certificate cert = keystore.getCertificate(certAlias);
    X509Certificate publicKey = (X509Certificate)cert;
    Key key = keystore.getKey(certAlias,certPw);
    PrivateKey privateKey = (PrivateKey)key;

    zipSigner.setKeys( "custom",publicKey,privateKey,signatureAlgorithm,null);
    zipSigner.signZip( inputZipFilename,outputZipFilename);
}
项目:jdk8u-jdk    文件SignatureBaseRSA.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);
    }
}
项目:mycat-src-1.6.1-RELEASE    文件DecryptUtil.java   
public static String encrypt(byte[] keyBytes,String plainText)
        throws Exception {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = factory.generatePrivate(spec);
    Cipher cipher = Cipher.getInstance("RSA");
       try {
        cipher.init(Cipher.ENCRYPT_MODE,privateKey);
       } catch (InvalidKeyException e) {
           //For IBM JDK,原因请看解密方法中的说明
           RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
           RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(),rsaPrivateKey.getPrivateExponent());
           Key fakePublicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec);
           cipher = Cipher.getInstance("RSA");
           cipher.init(Cipher.ENCRYPT_MODE,fakePublicKey);
       }

    byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
    String encryptedString = Base64.byteArrayToBase64(encryptedBytes);

    return encryptedString;
}
项目:epay    文件RSA.java   
/**
* RSA签名
* @param content 待签名数据
* @param privateKey 商户私钥
* @param input_charset 编码格式
* @return 签名值
*/
public static String sign(String content,String privateKey,String input_charset)
{
       try 
       {
        PKCS8EncodedKeySpec priPKCS8    = new PKCS8EncodedKeySpec( Base64.decode(privateKey) ); 
        KeyFactory keyf                 = KeyFactory.getInstance("RSA");
        PrivateKey priKey               = keyf.generatePrivate(priPKCS8);

           java.security.Signature signature = java.security.Signature
               .getInstance(SIGN_ALGORITHMS);

           signature.initSign(priKey);
           signature.update( content.getBytes(input_charset) );

           byte[] signed = signature.sign();

           return Base64.encode(signed);
       }
       catch (Exception e) 
       {
        e.printstacktrace();
       }

       return null;
   }
项目:q-mail    文件KeyChainKeyManager.java   
private PrivateKey fetchPrivateKey(Context context,String alias) throws KeyChainException,InterruptedException,MessagingException {

    PrivateKey privateKey = KeyChain.getPrivateKey(context,alias);
    if (privateKey == null) {
        throw new MessagingException("No private key found for: " + alias);
    }

    /*
     * We need to keep reference to the first private key retrieved so
     * it won't get garbage collected. If it will then the whole app
     * will crash on Android < 4.2 with "Fatal signal 11 code=1". See
     * https://code.google.com/p/android/issues/detail?id=62319
     */
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        savePrivateKeyReference(privateKey);
    }

    return privateKey;
}
项目:Openjsharp    文件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,ex);
    }
}
项目:buildAPKsSamples    文件KeyChainDemoActivity.java   
/**
 * This method prints the key chain @R_325_4045@ion.
 */
private void printInfo() {
    String alias = getAlias();
    X509Certificate[] certs = getCertificateChain(alias);
    final PrivateKey privateKey = getPrivateKey(alias);
    final StringBuffer sb = new StringBuffer();
    for (X509Certificate cert : certs) {
        sb.append(cert.getIssuerDN());
        sb.append("\n");
    }
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            TextView certTv = (TextView) findViewById(R.id.cert);
            TextView privateKeyTv = (TextView) findViewById(R.id.private_key);
            certTv.setText(sb.toString());
            privateKeyTv.setText(privateKey.getFormat() + ":" + privateKey);
        }
    });
}
项目:CrashCoin    文件TestWallet.java   
@Test
public void testBadPrivateKey()  throws IOException,FileNotFoundException,ClassNotFoundException,InvalidKeySpecException,InvalidKeyException,InvalidAlgorithmParameterException,IllegalBlockSizeException,InstantiationException {
    // Let wallet and keyPairs be the wallet and the pair of keys associated to user's account
    // and stored on the hard drive.
    final KeyPair keyPair = createKeyPair();

    // Let's suppose that an attacker entered a bad password and thus,got a bad DSA private key from
    // the decryption algorithm.
    final PrivateKey badPrivateKey = Cryptography.generateKeyPair().getPrivate();

    // The offline software must check whether this key is wrong or not. Let's do this by signing a
    // test transaction (it can be anything,let's write random bytes) and verify the signature.
    final byte[] transaction = randomBytes(156);
    final byte[] badSignature = Cryptography.signData(badPrivateKey,transaction);
    assertEquals(Cryptography.verifySignature(keyPair.getPublic(),transaction,badSignature),false);
}
项目:jdk8u-jdk    文件SignatureBaseRSA.java   
/** @inheritDoc */
protected void engineInitSign(Key privateKey,SecureRandom secureRandom)
    throws XMLSignatureException {
    if (!(privateKey instanceof PrivateKey)) {
        String supplied = privateKey.getClass().getName();
        String needed = PrivateKey.class.getName();
        Object exArgs[] = { supplied,exArgs);
    }

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey,secureRandom);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty",ex);
    }
}
项目:Openjsharp    文件SignatureECDSA.java   
/** @inheritDoc */
protected void engineInitSign(Key privateKey,ex);
    }
}
项目: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);
}
项目:Wurst-MC-1.12    文件Encryption.java   
private KeyPair loadRsaKeys(Path publicFile,Path privateFile)
    throws GeneralSecurityException,ReflectiveOperationException,IOException
{
    KeyFactory factory = KeyFactory.getInstance("RSA");

    // load public key
    PublicKey publicKey;
    try(ObjectInputStream in =
        new ObjectInputStream(Files.newInputStream(publicFile)))
    {
        publicKey = factory.generatePublic(new RSAPublicKeySpec(
            (BigInteger)in.readobject(),(BigInteger)in.readobject()));
    }

    // load private key
    PrivateKey privateKey;
    try(ObjectInputStream in =
        new ObjectInputStream(Files.newInputStream(privateFile)))
    {
        privateKey = factory.generatePrivate(new RSAPrivateKeySpec(
            (BigInteger)in.readobject(),(BigInteger)in.readobject()));
    }

    return new KeyPair(publicKey,privateKey);
}
项目:CS4160-trustchain-android    文件Key.java   
/**
 * 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;
}
项目:openjdk-jdk10    文件SignatureECDSA.java   
/** @inheritDoc */
protected void engineInitSign(Key privateKey,ex);
    }
}
项目:pay    文件AlipaySignature.java   
public static String rsa256Sign(String content,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_SHA256RSA_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 (Exception e) {
        throw new AlipayApiException("RSAcontent = " + content + "; charset = " + charset,e);
    }

}
项目:ipack    文件BaseKeyFactorySpi.java   
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof PKCS8EncodedKeySpec)
    {
        try
        {
            return generatePrivate(PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()));
        }
        catch (Exception e)
        {
            throw new InvalidKeySpecException("encoded key spec not recognised");
        }
    }
    else
    {
        throw new InvalidKeySpecException("key spec not recognised");
    }
}
项目:javaide    文件SignedJarBuilder.java   
/**
 * Creates a {@link SignedJarBuilder} with a given output stream,and signing @R_325_4045@ion.
 * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then
 * the archive will not be signed.
 * @param out the {@link OutputStream} where to write the Jar archive.
 * @param key the {@link PrivateKey} used to sign the archive,or <code>null</code>.
 * @param certificate the {@link X509Certificate} used to sign the archive,or
 * <code>null</code>.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public SignedJarBuilder(OutputStream out,PrivateKey key,X509Certificate certificate)
        throws IOException,NoSuchAlgorithmException {
    mOutputJar = new JarOutputStream(new bufferedoutputstream(out));
    mOutputJar.setLevel(9);
    mKey = key;
    mCertificate = certificate;

    if (mKey != null && mCertificate != null) {
        mManifest = new Manifest();
        Attributes main = mManifest.getMainAttributes();
        main.putValue("Manifest-Version","1.0");
        main.putValue("Created-By","1.0 (Android)");

        mBase64Encoder = new BASE64Encoder();
        mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
    }
}
项目:lemon-framework    文件RSAUtil.java   
/**
* RSA签名
* @param content 待签名数据
* @param privateKey 私钥
* @param input_charset 编码格式
* @return 签名值
*/
public static String sign(String content,String input_charset)
{
       try 
       {
        PKCS8EncodedKeySpec priPKCS8    = new PKCS8EncodedKeySpec( Base64Util.decode(privateKey) ); 
        KeyFactory keyf                 = KeyFactory.getInstance("RSA");
        PrivateKey priKey               = keyf.generatePrivate(priPKCS8);

           java.security.Signature signature = java.security.Signature
               .getInstance(SIGN_ALGORITHMS);

           signature.initSign(priKey);
           signature.update( content.getBytes(input_charset) );

           byte[] signed = signature.sign();

           return Base64Util.encode(signed);
       }
       catch (Exception e) 
       {
        logger.error(e.getMessage(),e);
       }

       return null;
   }
项目:mi-firma-android    文件CeresKeyStoreImpl.java   
/** {@inheritDoc} */
  @Override
  public KeyStore.Entry engineGetEntry(final String alias,final ProtectionParameter protParam) {
    if (protParam instanceof KeyStore.PasswordProtection) {
    final PasswordCallback pwc = new CachePasswordCallback(((KeyStore.PasswordProtection)protParam).getpassword());
    this.cryptoCard.setPasswordCallback(pwc);
    }
    if (!engineContainsAlias(alias)) {
        return null;
    }
    final PrivateKey key = (PrivateKey) engineGetKey(
    alias,null // Le pasamos null porque ya hemos establecido el PasswordCallback o el CallbackHander antes
);
    return new PrivateKeyEntry(key,engineGetCertificateChain(alias));
  }
项目:utilsLibrary    文件RSAUtils.java   
/**
 * RSA解密
 *
 * @param str str
 * @return 解密失败 会返回null
 */
public static String decryptStr(String str) {

    try {
        byte[] tmp = str.getBytes();
        tmp = Base64.decode(tmp,BASE64_FLAGS);
        PrivateKey privateKey = getPrivateKey(RSA_MODULUS,RSA_PRIVATE_EXPONENT);
        // 加解密类
        Cipher cipher = Cipher.getInstance("RSA"); // "RSA/ECB/PKCS1Padding"
        // 解密
        cipher.init(Cipher.DECRYPT_MODE,privateKey);
        byte[] dataDecode = cipher.doFinal(tmp);
        return new String(dataDecode);
    } catch (Exception e) {
        e.printstacktrace();
    }
    return null;
}
项目:Ships    文件DigitalSignature.java   
/**
 * Create a signature with the private key
 * @param data The data to sign
 * @return Base64 encoded signature
 */
public String sign(final String data) {
    final String tag = "sign - ";

    String result = null;

    try {
        Signature rsa = Signature.getInstance(CryptConstants.ALGORITHM_SIGNATURE);
        final PrivateKey key=retrievePrivateKey();
        if (key!=null) {
            rsa.initSign(key);
            rsa.update(data.getBytes());
            result = Base64.encodetoString(rsa.sign(),Base64.DEFAULT);
        }
    } catch (SignatureException | NoSuchAlgorithmException | InvalidKeyException e) {
        Log.e(TAG,tag,e);
    }

    return result;
}
项目:Openjsharp    文件PKCS8Key.java   
/**
 * Construct PKCS#8 subject public key from a DER value.  If
 * the runtime environment is configured with a specific class for
 * this kind of key,a subclass is returned.  Otherwise,a generic
 * PKCS8Key object is returned.
 *
 * <P>This mechanism gurantees that keys (and algorithms) may be
 * freely manipulated and transferred,without risk of losing
 * @R_325_4045@ion.  Also,when a key (or algorithm) needs some special
 * handling,that specific need can be accomodated.
 *
 * @param in the DER-encoded SubjectPublicKeyInfo value
 * @exception IOException on data format errors
 */
public static PrivateKey parseKey (DerValue in) throws IOException
{
    AlgorithmId algorithm;
    PrivateKey privKey;

    if (in.tag != DerValue.tag_Sequence)
        throw new IOException ("corrupt private key");

    BigInteger parsedVersion = in.data.getBigInteger();
    if (!version.equals(parsedVersion)) {
        throw new IOException("version mismatch: (supported: " +
                              Debug.toHexString(version) +
                              ",parsed: " +
                              Debug.toHexString(parsedVersion));
    }

    algorithm = AlgorithmId.parse (in.data.getDerValue ());

    try {
        privKey = buildPKCS8Key (algorithm,in.data.getoctetString ());

    } catch (InvalidKeyException e) {
        throw new IOException("corrupt private key");
    }

    if (in.data.available () != 0)
        throw new IOException ("excess private key");
    return privKey;
}
项目:ipack    文件KeyFactorySpi.java   
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof ElGamalPrivateKeySpec)
    {
        return new bcelGamalPrivateKey((ElGamalPrivateKeySpec)keySpec);
    }
    else if (keySpec instanceof DHPrivateKeySpec)
    {
        return new bcelGamalPrivateKey((DHPrivateKeySpec)keySpec);
    }

    return super.engineGeneratePrivate(keySpec);
}
项目:ipack    文件KeyFactorySpi.java   
protected PrivateKey engineGeneratePrivate(
        KeySpec    keySpec)
throws InvalidKeySpecException
{
    if (keySpec instanceof GOST3410PrivateKeySpec)
    {
        return new BCGOST3410PrivateKey((GOST3410PrivateKeySpec)keySpec);
    }

    return super.engineGeneratePrivate(keySpec);
}
项目:ipack    文件PKCS10CertificationRequest.java   
/**
 * create a PKCS10 certfication request using the named provider.
 */
public PKCS10CertificationRequest(
    String              signatureAlgorithm,X500Principal       subject,PublicKey           key,ASN1Set             attributes,PrivateKey          signingKey,String              provider)
    throws NoSuchAlgorithmException,NoSuchProviderException,SignatureException
{
    this(signatureAlgorithm,convertName(subject),key,attributes,signingKey,provider);
}
项目:mobile-store    文件LocalRepoKeyStore.java   
private Certificate generateSelfSignedCertChain(KeyPair kp,X500Name subject,String hostname)
        throws CertificateException,OperatorCreationException,IOException {
    SecureRandom rand = new SecureRandom();
    PrivateKey privKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();
    ContentSigner sigGen = new JcaContentSignerBuilder(DEFAULT_SIG_ALG).build(privKey);

    SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(
            ASN1Sequence.getInstance(pubKey.getEncoded()));

    Date Now = new Date(); // Now

    /* force it to use a English/Gregorian dates for the cert,hardly anyone
       ever looks at the cert Metadata anyway,and its very likely that they
       understand English/Gregorian dates */
    Calendar c = new GregorianCalendar(Locale.ENGLISH);
    c.setTime(Now);
    c.add(Calendar.YEAR,1);
    Time startTime = new Time(Now,Locale.ENGLISH);
    Time endTime = new Time(c.getTime(),Locale.ENGLISH);

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
            subject,BigInteger.valueOf(rand.nextLong()),startTime,endTime,subject,subPubKeyInfo);

    if (hostname != null) {
        GeneralNames subjectAltName = new GeneralNames(
                new GeneralName(GeneralName.iPAddress,hostname));
        v3CertGen.addExtension(X509Extension.subjectAlternativeName,false,subjectAltName);
    }

    X509CertificateHolder certHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
项目:mDL-ILP    文件ECCUtils.java   
/**
 * Extract the raw bytes of the private ECC key in standard smart card format.
 * @param privateKey the key to extract the bytes of.
 * @param curveReference the reference to the standard curve of the key.
 * @return the extract bytes of the key.
 */
public static byte[] decodeECCPrivateKeyPKCS8(PrivateKey privateKey,EllipticCurveParameters curveReference)
{
    byte[] privateKeyBytes = {};

    if (privateKey instanceof ECPrivateKey)
    {
        final byte[] s = getStandardSizeInteger(((ECPrivateKey)privateKey).getS().toByteArray(),curveReference);
        privateKeyBytes = s;
    }

    return privateKeyBytes;
}
项目:verify-hub    文件SamlEngineModule.java   
private PrivateKey privateSigningKey(SamlEngineConfiguration configuration) {
    // Running in production-like environments means we load keys from file descriptors
    // Non-prod environments may load keys from file paths
    if (configuration.shouldReadKeysFromFileDescriptors()) {
        return PrivateKeyFileDescriptors.SIGNING_KEY.loadKey();
    } else {
        return configuration.getPrivateSigningKeyConfiguration().getPrivateKey();
    }
}
项目:ipack    文件McElieceKeysToParams.java   
static public asymmetricKeyParameter generatePrivateKeyParameter(
    PrivateKey key)
    throws InvalidKeyException
{
    if (key instanceof BCMcEliecePrivateKey)
    {
        BCMcEliecePrivateKey k = (BCMcEliecePrivateKey)key;
        return new McEliecePrivateKeyParameters(k.getoIDString(),k.getN(),k.getK(),k.getField(),k.getGoppapoly(),k.getSInv(),k.getP1(),k.getP2(),k.getH(),k.getQInv(),k.getMcElieceParameters());
    }

    throw new InvalidKeyException("can't identify McEliece private key.");
}
项目:atlas    文件LocalSignedJarBuilder.java   
/**
 * Creates a {@link SignedJarBuilder} with a given output stream,and signing @R_325_4045@ion.
 * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then
 * the archive will not be signed.
 *
 * @param out         the {@link OutputStream} where to write the Jar archive.
 * @param key         the {@link PrivateKey} used to sign the archive,or
 *                    <code>null</code>.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public LocalSignedJarBuilder(@NonNull OutputStream out,@Nullable PrivateKey key,@Nullable X509Certificate certificate,@Nullable String builtBy,@Nullable String createdBy,@Nullable String signFile) throws IOException,NoSuchAlgorithmException {
    mOutputJar = new JarOutputStream(new bufferedoutputstream(out));
    mOutputJar.setLevel(9);
    mKey = key;
    mCertificate = certificate;
    mSignFile = signFile;

    if (mKey != null && mCertificate != null) {
        mManifest = new Manifest();
        Attributes main = mManifest.getMainAttributes();
        main.putValue("Manifest-Version","1.0");
        if (builtBy != null) {
            main.putValue("Built-By",builtBy);
        }
        if (createdBy != null) {
            main.putValue("Created-By",createdBy);
        }

        mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
    }
}
项目:talchain    文件ECKey.java   
private static PrivateKey privateKeyFromBigInteger(BigInteger priv) {
    if (priv == null) {
        return null;
    } else {
        try {
            return ECKeyFactory
                .getInstance(spongycastleProvider.getInstance())
                .generatePrivate(new ECPrivateKeySpec(priv,CURVE_SPEC));
        } catch (InvalidKeySpecException ex) {
            throw new AssertionError("Assumed correct key spec statically");
        }
    }
}
项目:firebase-admin-java    文件FirebasetokenFactory.java   
public String createSignedCustomAuthTokenForUser(
    String uid,Map<String,Object> developerClaims,String issuer,PrivateKey privateKey)
    throws GeneralSecurityException,IOException {
  Preconditions.checkState(uid != null,"Uid must be provided.");
  Preconditions.checkState(issuer != null && !"".equals(issuer),"Must provide an issuer.");
  Preconditions.checkState(uid.length() <= 128,"Uid must be shorter than 128 characters.");

  JsonWebSignature.Header header = new JsonWebSignature.Header().setAlgorithm("RS256");

  long issuedAt = clock.currentTimeMillis() / 1000;
  FirebaseCustomAuthToken.Payload payload =
      new FirebaseCustomAuthToken.Payload()
          .setUid(uid)
          .setIssuer(issuer)
          .setSubject(issuer)
          .setAudience(FirebaseCustomAuthToken.FIREBASE_AUDIENCE)
          .setIssuedAtTimeSeconds(issuedAt)
          .setExpirationTimeSeconds(issuedAt + FirebaseCustomAuthToken.TOKEN_DURATION_SECONDS);

  if (developerClaims != null) {
    Collection<String> reservednames = payload.getClassInfo().getNames();
    for (String key : developerClaims.keySet()) {
      if (reservednames.contains(key)) {
        throw new IllegalArgumentException(
            String.format("developer_claims can not contain a reserved key: %s",key));
      }
    }
    GenericJson jsonObject = new GenericJson();
    jsonObject.putAll(developerClaims);
    payload.setDeveloperClaims(jsonObject);
  }

  return JsonWebSignature.signUsingRsaSha256(privateKey,factory,header,payload);
}
项目:mi-firma-android    文件AOXAdESTriPhaseSigner.java   
@Override
public byte[] countersign(final byte[] sign,final String algorithm,final CounterSignTarget targettype,final Object[] targets,final PrivateKey key,final Certificate[] certChain,final Properties xParams) throws AOException {

    // Si no se ha definido nodos objeto de la contrafirma se definen los nodos hijo
    if (targettype == null) {
        throw new IllegalArgumentException("No se han indicado los nodos objetivo de la contrafirma"); //$NON-NLS-1$
    }

    // Comprobamos si es un tipo de contrafirma soportado
    if (targettype != CounterSignTarget.TREE && targettype != CounterSignTarget.LEAFS) {
        throw new UnsupportedOperationException("El objetivo indicado para la contrafirma no esta soportado: " + targettype); //$NON-NLS-1$
    }

    final Properties params = xParams != null ? xParams : new Properties();

    params.setProperty(COUNTERSIGN_TARGET_KEY,targettype.toString());

    return triPhaSEOperation(
        this.signFormat,CRYPTO_OPERATION_COUNTERSIGN,sign,algorithm,certChain,params
    );
}
项目:alipay-sdk    文件AlipaySignature.java   
public static PrivateKey getPrivateKeyFromPKCS8(String algorithm,InputStream ins) throws Exception {
    if (ins == null || StringUtils.isEmpty(algorithm)) {
        return null;
    }

    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);

    byte[] encodedKey = StreamUtil.readText(ins).getBytes();

    encodedKey = Base64.decodeBase64(encodedKey);

    return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
}
项目:GitHub    文件PubkeyBean.java   
public boolean changePassword(String oldPassword,String newPassword) throws Exception {
    PrivateKey priv;

    try {
        priv = PubkeyUtils.decodePrivate(getPrivateKey(),getType(),oldPassword);
    } catch (Exception e) {
        return false;
    }

    setPrivateKey(PubkeyUtils.getEncodedPrivate(priv,newPassword));
    setEncrypted(newPassword.length() > 0);

    return true;
}
项目:IJPay    文件SecureUtil.java   
/**
 * @param privateKey
 * @param cryptPin
 * @return
 * @throws Exception
 */
private static byte[] decryptData(PrivateKey privateKey,byte[] data)
        throws Exception {
    try {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding","BC");
        cipher.init(Cipher.DECRYPT_MODE,privateKey);
        return cipher.doFinal(data);
    } catch (Exception e) {
        LogUtil.writeErrorLog("解密失败",e);
    }
    return null;
}
项目: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          digestOID,String          sigProvider)
    throws NoSuchAlgorithmException,InvalidKeyException
{
    addSigner(key,subjectKeyID,digestOID,CMSUtils.getProvider(sigProvider));
}
项目:openjdk-jdk10    文件Basic.java   
private static int signAlias(int testnum,String alias) throws Exception {

        if (ks == null) {
            ks = KeyStore.getInstance(KS_TYPE,provider);
            ks.load(null,tokenPwd);
        }

        if (alias == null) {
            Enumeration enu = ks.aliases();
            if (enu.hasMoreElements()) {
                alias = (String)enu.nextElement();
            }
        }

        PrivateKey pkey = (PrivateKey)ks.getKey(alias,null);
        if ("RSA".equals(pkey.getAlgorithm())) {
            System.out.println("got [" + alias + "] signing key: " + pkey);
        } else {
            throw new SecurityException
                ("expected RSA,got " + pkey.getAlgorithm());
        }

        Signature s = Signature.getInstance("MD5WithRSA",ks.getProvider());
        s.initSign(pkey);
        System.out.println("initialized signature object with key");
        s.update("hello".getBytes());
        System.out.println("signature object updated with [hello] bytes");

        byte[] signed = s.sign();
        System.out.println("received signature " + signed.length +
                        " bytes in length");

        Signature v = Signature.getInstance("MD5WithRSA",ks.getProvider());
        v.initVerify(ks.getCertificate(alias));
        v.update("hello".getBytes());
        v.verify(signed);
        System.out.println("signature verified");
        System.out.println("test " + testnum++ + " passed");

        return testnum;
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。