Java Code Examples for java.security.PrivateKey

The following are top voted examples for showing how to use java.security.PrivateKey. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: mycat-src-1.6.1-RELEASE   File: DecryptUtil.java   Source Code and License 7 votes vote down vote up
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;
}
 
Example 2
Project: openjdk-jdk10   File: TestSignatures.java   Source Code and License 7 votes vote down vote up
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");
    }
}
 
Example 3
Project: openjdk-jdk10   File: DSAKeyFactory.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example 4
Project: javaide   File: CustomKeySigner.java   Source Code and License 6 votes vote down vote up
/** 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);
}
 
Example 5
Project: jdk8u-jdk   File: SignatureBaseRSA.java   Source Code and License 6 votes vote down vote up
/** @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);
    }
}
 
Example 6
Project: epay   File: RSA.java   Source Code and License 6 votes vote down vote up
/**
* 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;
   }
 
Example 7
Project: q-mail   File: KeyChainKeyManager.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 8
Project: OpenJSharp   File: SignatureDSA.java   Source Code and License 6 votes vote down vote up
/**
 * @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);
    }
}
 
Example 9
Project: buildAPKsSamples   File: KeyChainDemoActivity.java   Source Code and License 6 votes vote down vote up
/**
 * This method prints the key chain information.
 */
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);
        }
    });
}
 
Example 10
Project: CrashCoin   File: TestWallet.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 11
Project: jdk8u-jdk   File: SignatureBaseRSA.java   Source Code and License 6 votes vote down vote up
/** @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, needed };

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

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example 12
Project: OpenJSharp   File: SignatureECDSA.java   Source Code and License 6 votes vote down vote up
/** @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, needed };

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

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example 13
Project: ipack   File: CMSEnvelopedGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 14
Project: Wurst-MC-1.12   File: Encryption.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 15
Project: CS4160-trustchain-android   File: Key.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 16
Project: openjdk-jdk10   File: SignatureECDSA.java   Source Code and License 6 votes vote down vote up
/** @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, needed };

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

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example 17
Project: pay   File: AlipaySignature.java   Source Code and License 6 votes vote down vote up
public static String rsa256Sign(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_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);
    }

}
 
Example 18
Project: ipack   File: BaseKeyFactorySpi.java   Source Code and License 6 votes vote down vote up
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");
    }
}
 
Example 19
Project: javaide   File: SignedJarBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a {@link SignedJarBuilder} with a given output stream, and signing information.
 * <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);
    }
}
 
Example 20
Project: lemon-framework   File: RSAUtil.java   Source Code and License 6 votes vote down vote up
/**
* 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( 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;
   }
 
Example 21
Project: utilsLibrary   File: RSAUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 22
Project: Ships   File: DigitalSignature.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 23
Project: OpenJSharp   File: PKCS8Key.java   Source Code and License 5 votes vote down vote up
/**
 * 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
 * information.  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;
}
 
Example 24
Project: ipack   File: KeyFactorySpi.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 25
Project: ipack   File: KeyFactorySpi.java   Source Code and License 5 votes vote down vote up
protected PrivateKey engineGeneratePrivate(
        KeySpec    keySpec)
throws InvalidKeySpecException
{
    if (keySpec instanceof GOST3410PrivateKeySpec)
    {
        return new BCGOST3410PrivateKey((GOST3410PrivateKeySpec)keySpec);
    }

    return super.engineGeneratePrivate(keySpec);
}
 
Example 26
Project: ipack   File: PKCS10CertificationRequest.java   Source Code and License 5 votes vote down vote up
/**
 * 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,
            InvalidKeyException, SignatureException
{
    this(signatureAlgorithm, convertName(subject), key, attributes, signingKey, provider);
}
 
Example 27
Project: mobile-store   File: LocalRepoKeyStore.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 28
Project: mDL-ILP   File: ECCUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 29
Project: verify-hub   File: SamlEngineModule.java   Source Code and License 5 votes vote down vote up
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();
    }
}
 
Example 30
Project: ipack   File: McElieceKeysToParams.java   Source Code and License 5 votes vote down vote up
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.");
}
 
Example 31
Project: atlas   File: LocalSignedJarBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a {@link SignedJarBuilder} with a given output stream, and signing information.
 * <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 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);
    }
}
 
Example 32
Project: talchain   File: ECKey.java   Source Code and License 5 votes vote down vote up
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");
        }
    }
}
 
Example 33
Project: firebase-admin-java   File: FirebaseTokenFactory.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 34
Project: mi-firma-android   File: AOXAdESTriPhaseSigner.java   Source Code and License 5 votes vote down vote up
@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,
		key,
		certChain,
		params
	);
}
 
Example 35
Project: alipay-sdk   File: AlipaySignature.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 36
Project: GitHub   File: PubkeyBean.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 37
Project: IJPay   File: SecureUtil.java   Source Code and License 5 votes vote down vote up
/**
 * @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;
}
 
Example 38
Project: ipack   File: CMSSignedDataStreamGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * 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, NoSuchProviderException, InvalidKeyException
{
    addSigner(key, subjectKeyID, digestOID, CMSUtils.getProvider(sigProvider));
}
 
Example 39
Project: openjdk-jdk10   File: Basic.java   Source Code and License 5 votes vote down vote up
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;
    }
 
Example 40
Project: ipack   File: X509V2AttributeCertificateGenerator.java   Source Code and License 5 votes vote down vote up
/**
  * generate an X509 certificate, based on the current issuer and subject,
  * using the passed in provider for the signing.
  */
 public X509AttributeCertificate generate(
     PrivateKey      key,
     String          provider)
    throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, SignatureException, InvalidKeyException, NoSuchAlgorithmException
{
     return generate(key, provider, null);
 }
 
Example 41
Project: ipack   File: KeyFactorySpi.java   Source Code and License 5 votes vote down vote up
public PrivateKey generatePrivate(PrivateKeyInfo keyInfo)
    throws IOException
{
    ASN1ObjectIdentifier algOid = keyInfo.getPrivateKeyAlgorithm().getAlgorithm();

    if (DSAUtil.isDsaOid(algOid))
    {
        return new BCDSAPrivateKey(keyInfo);
    }
    else
    {
        throw new IOException("algorithm identifier " + algOid + " in key not recognised");
    }
}
 
Example 42
Project: utilsLibrary   File: RSAUtils.java   Source Code and License 5 votes vote down vote up
private static PrivateKey getPrivateKey(String modulus,
                                        String privateExponent) throws NoSuchAlgorithmException,
        InvalidKeySpecException {
    BigInteger bigIntModulus = new BigInteger(modulus);
    BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
    RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(bigIntModulus,
            bigIntPrivateExponent);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(keySpec);
}
 
Example 43
Project: nutz-pay   File: SecureUtil.java   Source Code and License 5 votes vote down vote up
/**
 * @param privateKey
 * @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) {
        log.error("解密失败", e);
    }
    return null;
}
 
Example 44
Project: CS4160-trustchain-android   File: Key.java   Source Code and License 5 votes vote down vote up
/**
 * Load a private key from the given file
 * @param context The context (needed to read the file)
 * @param file The file
 * @return The private key
 */
public static PrivateKey loadPrivateKey(Context context, String file) {
    String key = Util.readFile(context, file);
    if(key == null) {
        return null;
    }
    Log.i(TAG, "PRIVATE FROM FILE: " + key);
    return loadPrivateKey(key);
}
 
Example 45
Project: mi-firma-android   File: CeresSignatureImpl.java   Source Code and License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void engineInitSign(final PrivateKey prKey) throws InvalidKeyException {
    if (prKey == null) {
        throw new InvalidKeyException("La clave proporcionada es nula"); //$NON-NLS-1$
    }
    if (!(prKey instanceof CeresPrivateKey)) {
        throw new InvalidKeyException("La clave proporcionada no es de una tarjeta CERES: " + prKey.getClass().getName()); //$NON-NLS-1$
    }
    this.privateKey = (CeresPrivateKey) prKey;
    this.data.reset();
}
 
Example 46
Project: ipack   File: CMSSignedDataStreamGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * add a signer with extra signed/unsigned attributes.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @deprecated use addSignerInfoGenerator
 */
public void addSigner(
    PrivateKey      key,
    byte[]          subjectKeyID,
    String          digestOID,
    AttributeTable  signedAttr,
    AttributeTable  unsignedAttr,
    Provider        sigProvider)
    throws NoSuchAlgorithmException, InvalidKeyException
{
    addSigner(key, subjectKeyID, digestOID,
        new DefaultSignedAttributeTableGenerator(signedAttr),
        new SimpleAttributeTableGenerator(unsignedAttr), sigProvider);
}
 
Example 47
Project: HerbertyyRepository   File: RSAUtils.java   Source Code and License 5 votes vote down vote up
public static void printPrivateKeyInfo(PrivateKey privateKey)
{
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
    System.out.println("----------RSAPrivateKey ----------");
    System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
    System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
    System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
    System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());

}
 
Example 48
Project: xitk   File: P11RSADigestSignatureSpi.java   Source Code and License 5 votes vote down vote up
@Override
protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
    if (!(privateKey instanceof P11PrivateKey)) {
        throw new InvalidKeyException("privateKey is not instanceof "
                + P11PrivateKey.class.getName());
    }

    String algo = privateKey.getAlgorithm();
    if (!"RSA".equals(algo)) {
        throw new InvalidKeyException("privateKey is not an RSA private key: " + algo);
    }

    digest.reset();
    this.signingKey = (P11PrivateKey) privateKey;
}
 
Example 49
Project: FApkSigner   File: ApkSigner.java   Source Code and License 5 votes vote down vote up
/**
 * Constructs a new {@code Builder}.
 *
 * @param name signer's name. The name is reflected in the name of files comprising the
 *        JAR signature of the APK.
 * @param privateKey signing key
 * @param certificates list of one or more X.509 certificates. The subject public key of
 *        the first certificate must correspond to the {@code privateKey}.
 */
public Builder(
        String name,
        PrivateKey privateKey,
        List<X509Certificate> certificates) {
    if (name.isEmpty()) {
        throw new IllegalArgumentException("Empty name");
    }
    mName = name;
    mPrivateKey = privateKey;
    mCertificates = new ArrayList<>(certificates);
}
 
Example 50
Project: ipack   File: NetscapeCertRequest.java   Source Code and License 5 votes vote down vote up
public void sign(PrivateKey priv_key, SecureRandom rand)
        throws NoSuchAlgorithmException, InvalidKeyException,
        SignatureException, NoSuchProviderException,
        InvalidKeySpecException
{
    Signature sig = Signature.getInstance(sigAlg.getAlgorithm().getId(),
            "BC");

    if (rand != null)
    {
        sig.initSign(priv_key, rand);
    }
    else
    {
        sig.initSign(priv_key);
    }

    ASN1EncodableVector pkac = new ASN1EncodableVector();

    pkac.add(getKeySpec());
    pkac.add(new DERIA5String(challenge));

    try
    {
        sig.update(new DERSequence(pkac).getEncoded(ASN1Encoding.DER));
    }
    catch (IOException ioe)
    {
        throw new SignatureException(ioe.getMessage());
    }

    sigBits = sig.sign();
}
 
Example 51
Project: FApkSigner   File: DefaultApkSignerEngine.java   Source Code and License 5 votes vote down vote up
/**
 * Constructs a new {@code Builder}.
 *
 * @param name signer's name. The name is reflected in the name of files comprising the
 *        JAR signature of the APK.
 * @param privateKey signing key
 * @param certificates list of one or more X.509 certificates. The subject public key of
 *        the first certificate must correspond to the {@code privateKey}.
 */
public Builder(
        String name,
        PrivateKey privateKey,
        List<X509Certificate> certificates) {
    if (name.isEmpty()) {
        throw new IllegalArgumentException("Empty name");
    }
    mName = name;
    mPrivateKey = privateKey;
    mCertificates = new ArrayList<>(certificates);
}
 
Example 52
Project: openjdk-jdk10   File: PKCS8Key.java   Source Code and License 5 votes vote down vote up
/**
 * 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
 * information.  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;
}
 
Example 53
Project: mi-firma-android   File: AOXAdESASiCSTriPhaseSigner.java   Source Code and License 5 votes vote down vote up
@Override
public byte[] cosign(final byte[] data,
		             final byte[] sign,
		             final String algorithm,
		             final PrivateKey key,
		             final Certificate[] certChain,
		             final Properties xParams) throws AOException {
	throw new UnsupportedOperationException("No se soportan cofirmas trifasicas XAdES-ASiC-S"); //$NON-NLS-1$
}
 
Example 54
Project: springboot-shiro-cas-mybatis   File: AbstractSamlObjectBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * Sign SAML response.
 *
 * @param samlResponse the SAML response
 * @param privateKey the private key
 * @param publicKey the public key
 * @return the response
 */
public final String signSamlResponse(final String samlResponse,
                                     final PrivateKey privateKey, final PublicKey publicKey) {
    final Document doc = constructDocumentFromXml(samlResponse);

    if (doc != null) {
        final org.jdom.Element signedElement = signSamlElement(doc.getRootElement(),
                privateKey, publicKey);
        doc.setRootElement((org.jdom.Element) signedElement.detach());
        return new XMLOutputter().outputString(doc);
    }
    throw new RuntimeException("Error signing SAML Response: Null document");
}
 
Example 55
Project: ipack   File: X509V2AttributeCertificateGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * generate an X509 certificate, based on the current issuer and subject,
 * using the passed in provider for the signing.
 * @deprecated use generate()
 */
public X509AttributeCertificate generateCertificate(
    PrivateKey      key,
    String          provider)
    throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException
{
    return generateCertificate(key, provider, null);
}
 
Example 56
Project: jdk8u-jdk   File: Offsets.java   Source Code and License 5 votes vote down vote up
private Offsets(Signature signature, PublicKey pubkey, PrivateKey privkey,
        int size, byte[] cleartext) throws InvalidKeyException,
            SignatureException {
    this.pubkey = pubkey;
    this.signature = signature;
    this.size = size;
    this.cleartext = cleartext;

    signature.initSign(privkey);
    signature.update(cleartext, 0, size);
    signed = signature.sign();
}
 
Example 57
Project: wolfcrypt-jni   File: WolfCryptSignatureTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testInteropSignWolfVerify()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           SignatureException, InvalidKeyException,
           InvalidAlgorithmParameterException {

    String toSign = "Hello World";
    byte[] toSignBuf = toSign.getBytes();
    byte[] signature;

    for (int i = 0; i < wolfJCEAlgos.length; i++) {

        Signature signer =
            Signature.getInstance(wolfJCEAlgos[i]);
        Signature verifier =
            Signature.getInstance(wolfJCEAlgos[i], "wolfJCE");

        assertNotNull(signer);
        assertNotNull(verifier);

        Provider prov = signer.getProvider();
        if (prov.equals("wolfJCE")) {
            /* bail out, there isn't another implementation to interop
             * against by default */
            return;
        }

        SecureRandom rand =
            SecureRandom.getInstance("HashDRBG", "wolfJCE");
        assertNotNull(rand);

        /* generate key pair */
        KeyPair pair = generateKeyPair(wolfJCEAlgos[i], rand);
        assertNotNull(pair);

        PrivateKey priv = pair.getPrivate();
        PublicKey  pub  = pair.getPublic();

        /* generate signature */
        signer.initSign(priv);
        signer.update(toSignBuf, 0, toSignBuf.length);
        signature = signer.sign();

        /* verify signature */
        verifier.initVerify(pub);
        verifier.update(toSignBuf, 0, toSignBuf.length);
        boolean verified = verifier.verify(signature);

        if (verified != true) {
            fail("Signature verification failed when generating with " +
                    "system default JCE provider and verifying with " +
                    "wolfJCE provider, iteration " + i);
        }
    }
}
 
Example 58
Project: mi-firma-android   File: AOXAdESASiCSTriPhaseSigner.java   Source Code and License 5 votes vote down vote up
@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 {

	throw new UnsupportedOperationException("No se soportan contrafirmas trifasicas XAdES-ASiC-S"); //$NON-NLS-1$
}
 
Example 59
Project: xitk   File: P11ProviderSm2TestCmd.java   Source Code and License 5 votes vote down vote up
@Override
protected Object execute0() throws Exception {
    KeyStore ks = KeyStore.getInstance("PKCS11", XiSecurityConstants.PROVIDER_NAME_XIPKI);
    ks.load(null, null);
    if (verbose.booleanValue()) {
        println("available aliases:");
        Enumeration<?> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alias2 = (String) aliases.nextElement();
            println("    " + alias2);
        }
    }

    String alias = getAlias();
    println("alias: " + alias);
    PrivateKey key = (PrivateKey) ks.getKey(alias, null);
    if (key == null) {
        println("could not find key with alias '" + alias + "'");
        return null;
    }

    Certificate cert = ks.getCertificate(alias);
    if (cert == null) {
        println("could not find certificate to verify signature");
        return null;
    }
    PublicKey pubKey = cert.getPublicKey();

    String sigAlgo = "SM3withSM2";
    println("signature algorithm: " + sigAlgo);
    Signature sig = Signature.getInstance(sigAlgo, XiSecurityConstants.PROVIDER_NAME_XIPKI);

    if (StringUtil.isNotBlank(ida)) {
        sig.setParameter(new XiSM2ParameterSpec(ida.getBytes()));
    }

    sig.initSign(key);

    byte[] data = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    sig.update(data);
    byte[] signature = sig.sign(); // CHECKSTYLE:SKIP
    println("signature created successfully");

    Signature ver = Signature.getInstance(sigAlgo, "BC");
    if (StringUtil.isNotBlank(ida)) {
        ver.setParameter(new SM2ParameterSpec(ida.getBytes()));
    }

    ver.initVerify(pubKey);
    ver.update(data);
    boolean valid = ver.verify(signature);
    println("signature valid: " + valid);
    return null;
}
 
Example 60
Project: mi-firma-android   File: CeresKeyStoreImpl.java   Source Code and License 5 votes vote down vote up
/** {@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));
  }