Java Code Examples for java.security.PrivateKey#getAlgorithm()

The following examples show how to use java.security.PrivateKey#getAlgorithm() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Pair a private key with a public EC point.
 * <p>
 * All private key operations will use the provider.
 */
public ECKey(Provider provider, PrivateKey privKey, ECPoint pub) {
    this.provider = provider;

    if (privKey == null || isECPrivateKey(privKey)) {
        this.privKey = privKey;
    } else {
        throw new IllegalArgumentException(
                "Expected EC private key, given a private key object with class " +
                        privKey.getClass().toString() +
                        " and algorithm " + privKey.getAlgorithm());
    }

    if (pub == null) {
        throw new IllegalArgumentException("Public key may not be null");
    } else {
        this.pub = pub;
    }
}
 
Example 2
Source File: KeyUtils.java    From vespa with Apache License 2.0 6 votes vote down vote up
private static String toPkcs1Pem(PrivateKey privateKey) {
    try (StringWriter stringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) {
        String algorithm = privateKey.getAlgorithm();
        String type;
        if (algorithm.equals(RSA.getAlgorithmName())) {
            type = "RSA PRIVATE KEY";
        } else if (algorithm.equals(EC.getAlgorithmName())) {
            type = "EC PRIVATE KEY";
        } else {
            throw new IllegalArgumentException("Unexpected key algorithm: " + algorithm);
        }
        pemWriter.writeObject(new PemObject(type, getPkcs1Bytes(privateKey)));
        pemWriter.flush();
        return stringWriter.toString();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 3
Source File: P11RSAPSSSignatureSpi.java    From xipki with Apache License 2.0 6 votes vote down vote up
protected void engineInitSign(PrivateKey privateKey, SecureRandom random)
    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);
  }

  this.signingKey = (P11PrivateKey) privateKey;

  pss = new org.bouncycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest,
      saltLength, trailer);

  P11RSAKeyParameter p11KeyParam = P11RSAKeyParameter.getInstance(
      signingKey.getP11CryptService(), signingKey.getIdentityId());
  if (random == null) {
    pss.init(true, p11KeyParam);
  } else {
    pss.init(true, new ParametersWithRandom(p11KeyParam, random));
  }
}
 
Example 4
Source File: ECKey.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Pair a private key with a public EC point.
 *
 * <p>All private key operations will use the provider.
 */

public ECKey(Provider provider, @Nullable PrivateKey privKey, ECPoint pub) {
    this.provider = provider;

    if (privKey == null || isECPrivateKey(privKey)) {
        this.privKey = privKey;
    } else {
        throw new IllegalArgumentException(
                "Expected EC private key, given a private key object with" +
                        " class "
                        + privKey.getClass().toString() +
                        " and algorithm "
                        + privKey.getAlgorithm());
    }

    if (pub == null) {
        throw new IllegalArgumentException("Public key may not be null");
    } else {
        this.pub = pub;
    }
}
 
Example 5
Source File: ECKey.java    From tron-wallet-android with Apache License 2.0 6 votes vote down vote up
/**
 * Pair a private key with a public EC point. <p> All private key operations will use the
 * provider.
 */
public ECKey(Provider provider, @Nullable PrivateKey privKey, ECPoint pub) {
  this.provider = provider;

  if (privKey == null || isECPrivateKey(privKey)) {
    this.privKey = privKey;
  } else {
    throw new IllegalArgumentException(
        "Expected EC private key, given a private key object with" +
            " class " +
            privKey.getClass().toString() +
            " and algorithm " + privKey.getAlgorithm());
  }

  if (pub == null) {
    throw new IllegalArgumentException("Public key may not be null");
  } else {
    this.pub = pub;
  }
}
 
Example 6
Source File: ECKey.java    From asf-sdk with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Pair a private key with a public EC point.
 *
 * All private key operations will use the provider.
 */
public ECKey(Provider provider, @Nullable PrivateKey privKey, ECPoint pub) {
  this.provider = provider;

  if (privKey == null || isECPrivateKey(privKey)) {
    this.privKey = privKey;
  } else {
    throw new IllegalArgumentException(
        "Expected EC private key, given a private key object with class "
            + privKey.getClass()
            + " and algorithm "
            + privKey.getAlgorithm());
  }

  if (pub == null) {
    throw new IllegalArgumentException("Public key may not be null");
  } else {
    this.pub = pub;
  }
}
 
Example 7
Source File: SignatureUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Sign a string using the private key
 *
 * @param stringToBeSigned
 * @param signingKey
 *
 * @return
 *
 * @throws GeneralSecurityException
 */
public static byte[] sign(String stringToBeSigned, PrivateKey signingKey) throws GeneralSecurityException {
    if (stringToBeSigned == null)
        throw logger.nullArgumentError("stringToBeSigned");
    if (signingKey == null)
        throw logger.nullArgumentError("signingKey");

    String algo = signingKey.getAlgorithm();
    Signature sig = getSignature(algo);
    sig.initSign(signingKey);
    sig.update(stringToBeSigned.getBytes(GeneralConstants.SAML_CHARSET));
    return sig.sign();
}
 
Example 8
Source File: ScepUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static String getSignatureAlgorithm(PrivateKey key, HashAlgo hashAlgo) {
  Args.notNull(key, "key");
  Args.notNull(hashAlgo, "hashAlgo");
  String algorithm = key.getAlgorithm();
  if ("RSA".equalsIgnoreCase(algorithm)) {
    return hashAlgo.getName() + "withRSA";
  } else {
    throw new UnsupportedOperationException(
        "getSignatureAlgorithm() for non-RSA is not supported yet.");
  }
}
 
Example 9
Source File: CaClientExample.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static ContentSigner buildSigner(PrivateKey signingKey, String hashAlgo)
    throws OperatorCreationException {
  String keyAlgo = signingKey.getAlgorithm();
  String sigAlgo;
  if ("EC".equalsIgnoreCase(keyAlgo)) {
    sigAlgo = hashAlgo + "WITHECDSA";
  } else {
    sigAlgo = hashAlgo + "WITH" + keyAlgo;
  }
  return new JcaContentSignerBuilder(sigAlgo).build(signingKey);
}
 
Example 10
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static String getSignatureAlgorithm(PrivateKey key, ASN1ObjectIdentifier digestOid) {
  HashAlgo hashAlgo = HashAlgo.getInstance(digestOid.getId());
  if (hashAlgo == null) {
    hashAlgo = HashAlgo.SHA256;
  }
  String algorithm = key.getAlgorithm();
  if ("RSA".equalsIgnoreCase(algorithm)) {
    return hashAlgo.getName() + "withRSA";
  } else {
    throw new UnsupportedOperationException(
        "getSignatureAlgorithm() for non-RSA is not supported yet.");
  }
}
 
Example 11
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compare the supplied public and private keys, and determine if they correspond to the same key pair.
 * 
 * @param pubKey the public key
 * @param privKey the private key
 * @return true if the public and private are from the same key pair, false if not
 * @throws SecurityException if the keys can not be evaluated, or if the key algorithm is unsupported or unknown
 */
public static boolean matchKeyPair(PublicKey pubKey, PrivateKey privKey) throws SecurityException {
    Logger log = getLogger();
    // This approach attempts to match the keys by signing and then validating some known data.

    if (pubKey == null || privKey == null) {
        throw new SecurityException("Either public or private key was null");
    }

    // Need to dynamically determine the JCA signature algorithm ID to use from the key algorithm.
    // Don't currently have a direct mapping, so have to map to XML Signature algorithm URI first,
    // then map that to JCA algorithm ID.
    SecurityConfiguration secConfig = Configuration.getGlobalSecurityConfiguration();
    if (secConfig == null) {
        throw new SecurityException("Global security configuration was null, could not resolve signing algorithm");
    }
    String algoURI = secConfig.getSignatureAlgorithmURI(privKey.getAlgorithm());
    if (algoURI == null) {
        throw new SecurityException("Can't determine algorithm URI from key algorithm: " + privKey.getAlgorithm());
    }
    String jcaAlgoID = getAlgorithmIDFromURI(algoURI);
    if (jcaAlgoID == null) {
        throw new SecurityException("Can't determine JCA algorithm ID from algorithm URI: " + algoURI);
    }

    if (log.isDebugEnabled()) {
        log.debug("Attempting to match key pair containing key algorithms public '{}' private '{}', "
                + "using JCA signature algorithm '{}'", new Object[] { pubKey.getAlgorithm(),
                privKey.getAlgorithm(), jcaAlgoID, });
    }

    byte[] data = "This is the data to sign".getBytes();
    byte[] signature = SigningUtil.sign(privKey, jcaAlgoID, data);
    return SigningUtil.verify(pubKey, jcaAlgoID, signature, data);
}
 
Example 12
Source File: P11RSADigestSignatureSpi.java    From xipki with Apache License 2.0 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 13
Source File: Basic.java    From openjdk-jdk8u with GNU General Public License v2.0 4 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 14
Source File: P11DSASignatureSpi.java    From xipki with Apache License 2.0 4 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 (!"DSA".equals(algo)) {
    throw new InvalidKeyException("privateKey is not a DSA private key: " + algo);
  }

  this.signingKey = (P11PrivateKey) privateKey;
  if (signingKey.supportsMechanism(PKCS11Constants.CKM_DSA)) {
    mechanism = PKCS11Constants.CKM_DSA;
    if (hashAlgo == null) {
      outputStream = new ByteArrayOutputStream();
    } else {
      outputStream = new DigestOutputStream(hashAlgo.createDigest());
    }
  } else {
    if (hashAlgo == HashAlgo.SHA1
        && signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA1)) {
      mechanism = PKCS11Constants.CKM_DSA_SHA1;
    } else if (hashAlgo == HashAlgo.SHA224
        && signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA224)) {
      mechanism = PKCS11Constants.CKM_DSA_SHA224;
    } else if (hashAlgo == HashAlgo.SHA256
        && signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA256)) {
      mechanism = PKCS11Constants.CKM_DSA_SHA256;
    } else if (hashAlgo == HashAlgo.SHA384
        && signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA384)) {
      mechanism = PKCS11Constants.CKM_DSA_SHA384;
    } else if (hashAlgo == HashAlgo.SHA512
        && signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA512)) {
      mechanism = PKCS11Constants.CKM_DSA_SHA512;
    } else if (hashAlgo == HashAlgo.SHA3_224
        && signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA3_224)) {
      mechanism = PKCS11Constants.CKM_DSA_SHA3_224;
    } else if (hashAlgo == HashAlgo.SHA3_256
        && signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA3_256)) {
      mechanism = PKCS11Constants.CKM_DSA_SHA3_256;
    } else if (hashAlgo == HashAlgo.SHA3_384
        && signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA3_384)) {
      mechanism = PKCS11Constants.CKM_DSA_SHA3_384;
    } else if (hashAlgo == HashAlgo.SHA3_512
        && signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA3_512)) {
      mechanism = PKCS11Constants.CKM_DSA_SHA3_512;
    } else {
      throw new InvalidKeyException("privateKey and algorithm does not match");
    }

    outputStream = new ByteArrayOutputStream();
  }

  this.signingKey = (P11PrivateKey) privateKey;
}
 
Example 15
Source File: Basic.java    From jdk8u60 with GNU General Public License v2.0 4 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 16
Source File: SignatureStructImpl.java    From ID-SDK with Apache License 2.0 4 votes vote down vote up
public SignatureStructImpl(byte[] payload, PrivateKey privateKey) throws IdentifierException {
	this.payload = payload;
	keyAlg = privateKey.getAlgorithm();
	if ("RSA".equals(keyAlg)) {
		hashAlg = "SHA256";
		header = Util.encodeString("{\"alg\":\"RS256\"}");
	} else if ("DSA".equals(keyAlg)) {
		hashAlg = "SHA1";
		header = Util.encodeString("{\"alg\":\"DS160\"}");
	} else if ("EC".equals(keyAlg)){
      	 	hashAlg = "SM3";
      	 	header = Util.encodeString("{\"alg\":\"SM2SM3\"}");
	}else {
		throw new IllegalArgumentException("未知算法: " + keyAlg);
	}
	based64_Header = Base64.encodeBase64URLSafe(header);
	based64_Payload = Base64.encodeBase64URLSafe(payload);
	try {
		if("EC".equals(keyAlg)){
			SM2Tool sm2Tool = new SM2Tool();
       		byte[] bDot = new byte[]{(byte)'.'};
       		byte[] signData = Util.join(based64_Header,bDot,based64_Payload);
       		String data = new String(signData);
       		String id = "1234567812345678";
       		BigInteger prvKey = ((BCECPrivateKey) privateKey).getD();
       		ECPoint pubkey = sm2Tool.G.multiply(prvKey).normalize();
       		cn.ac.caict.iiiiot.id.client.security.gm.SM2Tool.Signature sign = sm2Tool.sign(data, id, new SM2KeyPair(pubkey,prvKey));
       		//signature转为byte[]
       		byte[] bR = sign.r.toByteArray();
       		byte[] bS = sign.s.toByteArray();
       		signature = BaseConvertor.signatureFormat(bR,bS);
       		//将byte[]用Base64编码
       		based64_Signature = Base64.encodeBase64URLSafe(signature);
		} else {
			Signature sig = Signature.getInstance(hashAlg + "with" + keyAlg);
			sig.initSign(privateKey);
			sig.update(based64_Header);
			sig.update((byte) '.');
			sig.update(based64_Payload);
			signature = sig.sign();
			based64_Signature = Base64.encodeBase64URLSafe(signature);
		}
		
	} catch (Exception e) {
		throw new IdentifierException(ExceptionCommon.EXCEPTIONCODE_SECURITY_ALERT, "构建签名数据失败");
	}
}
 
Example 17
Source File: P11SM3WithSM2SignatureSpi.java    From xipki with Apache License 2.0 4 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());
  }

  this.signingKey = (P11PrivateKey) privateKey;
  if (!(signingKey.getPublicKey() instanceof ECPublicKey)) {
    throw new InvalidKeyException("only EC key is allowed");
  }

  ECPublicKey pubKey = (ECPublicKey) signingKey.getPublicKey();
  if (!GMUtil.isSm2primev2Curve(pubKey.getParams().getCurve())) {
    throw new InvalidKeyException("only EC key of curve sm2primev2 is allowed");
  }

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

  byte[] userId = (paramSpec == null)
      ? StringUtil.toUtf8Bytes("1234567812345678") : paramSpec.getId();

  if (signingKey.supportsMechanism(PKCS11Constants.CKM_VENDOR_SM2)) {
    mechanism = PKCS11Constants.CKM_VENDOR_SM2;
    outputStream = new DigestOutputStream(HashAlgo.SM3.createDigest());
    p11Params = null;

    ECPoint w = pubKey.getW();

    sm2Z = GMUtil.getSM2Z(userId, GMObjectIdentifiers.sm2p256v1, w.getAffineX(), w.getAffineY());
    try {
      outputStream.write(sm2Z, 0, sm2Z.length);
    } catch (IOException ex) {
      throw new InvalidKeyException("could not compute Z of SM2");
    }
  } else if (signingKey.supportsMechanism(PKCS11Constants.CKM_VENDOR_SM2_SM3)) {
    mechanism = PKCS11Constants.CKM_VENDOR_SM2_SM3;
    outputStream = new ByteArrayOutputStream();
    p11Params = new P11ByteArrayParams(userId);
  } else {
    throw new InvalidKeyException("privateKey and algorithm does not match");
  }

  this.signingKey = (P11PrivateKey) privateKey;
}
 
Example 18
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Generates a signature.
 * @param privKey the private key
 * @param certChain the certificate chain
 * @param crlList the certificate revocation list
 * @param hashAlgorithm the hash algorithm
 * @param provider the provider or <code>null</code> for the default provider
 * @param hasRSAdata <CODE>true</CODE> if the sub-filter is adbe.pkcs7.sha1
 * @throws InvalidKeyException on error
 * @throws NoSuchProviderException on error
 * @throws NoSuchAlgorithmException on error
 */    
public PdfPKCS7(PrivateKey privKey, Certificate[] certChain, CRL[] crlList,
                String hashAlgorithm, String provider, boolean hasRSAdata)
  throws InvalidKeyException, NoSuchProviderException,
  NoSuchAlgorithmException
{
    this.privKey = privKey;
    this.provider = provider;
    
    digestAlgorithm = (String)allowedDigests.get(hashAlgorithm.toUpperCase());
    if (digestAlgorithm == null)
        throw new NoSuchAlgorithmException("Unknown Hash Algorithm "+hashAlgorithm);
    
    version = signerversion = 1;
    certs = new ArrayList();
    crls = new ArrayList();
    digestalgos = new HashSet();
    digestalgos.add(digestAlgorithm);
    
    //
    // Copy in the certificates and crls used to sign the private key.
    //
    signCert = (X509Certificate)certChain[0];
    for (int i = 0;i < certChain.length;i++) {
        certs.add(certChain[i]);
    }
    
    if (crlList != null) {
        for (int i = 0;i < crlList.length;i++) {
            crls.add(crlList[i]);
        }
    }
    
    if (privKey != null) {
        //
        // Now we have private key, find out what the digestEncryptionAlgorithm is.
        //
        digestEncryptionAlgorithm = privKey.getAlgorithm();
        if (digestEncryptionAlgorithm.equals("RSA")) {
            digestEncryptionAlgorithm = ID_RSA;
        }
        else if (digestEncryptionAlgorithm.equals("DSA")) {
            digestEncryptionAlgorithm = ID_DSA;
        }
        else {
            throw new NoSuchAlgorithmException("Unknown Key Algorithm "+digestEncryptionAlgorithm);
        }
    }
    if (hasRSAdata) {
        RSAdata = new byte[0];
        if (provider == null || provider.startsWith("SunPKCS11"))
            messageDigest = MessageDigest.getInstance(getHashAlgorithm());
        else
            messageDigest = MessageDigest.getInstance(getHashAlgorithm(), provider);
    }

    if (privKey != null) {
        if (provider == null)
            sig = Signature.getInstance(getDigestAlgorithm());
        else
            sig = Signature.getInstance(getDigestAlgorithm(), provider);

        sig.initSign(privKey);
    }
}
 
Example 19
Source File: Basic.java    From hottub with GNU General Public License v2.0 4 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 20
Source File: Basic.java    From dragonwell8_jdk with GNU General Public License v2.0 4 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;
    }