Java Code Examples for java.security.Signature#getInstance()

The following examples show how to use java.security.Signature#getInstance() . 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: WeakMessageDigestAdditionalSig.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void weakDigestMoreSig() throws NoSuchProviderException, NoSuchAlgorithmException {
    MessageDigest.getInstance("MD5", "SUN");
    MessageDigest.getInstance("MD4", "SUN");
    MessageDigest.getInstance("MD2", "SUN");
    MessageDigest.getInstance("MD5");
    MessageDigest.getInstance("MD4");
    MessageDigest.getInstance("MD2");
    MessageDigest.getInstance("MD5", new DummyProvider());
    MessageDigest.getInstance("MD4", new DummyProvider());
    MessageDigest.getInstance("MD2", new DummyProvider());
    MessageDigest.getInstance("SHA", "SUN");
    MessageDigest.getInstance("SHA", new DummyProvider());
    MessageDigest.getInstance("SHA1", "SUN");
    MessageDigest.getInstance("SHA1", new DummyProvider());
    MessageDigest.getInstance("SHA-1", "SUN");
    MessageDigest.getInstance("SHA-1", new DummyProvider());
    MessageDigest.getInstance("sha-384","SUN"); //OK!
    MessageDigest.getInstance("SHA-512", "SUN"); //OK!
    
    Signature.getInstance("MD5withRSA");
    Signature.getInstance("MD2withDSA", "X");
    Signature.getInstance("SHA1withRSA", new DummyProvider());
    Signature.getInstance("SHA256withRSA"); //OK
    Signature.getInstance("uncommon name", ""); //OK
}
 
Example 2
Source File: TLSTest.java    From cava with Apache License 2.0 6 votes vote down vote up
private void checkKeyPair(Path key, Path cert) throws Exception {
  PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(readPemFile(key));
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(Files.readAllBytes(cert)));
  KeyFactory kf = KeyFactory.getInstance("RSA");
  KeyPair keyPair = new KeyPair(certificate.getPublicKey(), kf.generatePrivate(pkcs8KeySpec));

  byte[] challenge = new byte[10000];
  ThreadLocalRandom.current().nextBytes(challenge);

  // sign using the private key
  Signature sig = Signature.getInstance("SHA256withRSA");
  sig.initSign(keyPair.getPrivate());
  sig.update(challenge);
  byte[] signature = sig.sign();

  // verify signature using the public key
  sig.initVerify(keyPair.getPublic());
  sig.update(challenge);

  assertTrue(sig.verify(signature));
}
 
Example 3
Source File: RevocationAuthority.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that the revocation PK for a certain epoch is valid,
 * by checking that it was signed with the long term revocation key
 *
 * @param pk         Public Key
 * @param epochPK    Epoch PK
 * @param epochPkSig Epoch PK Signature
 * @param epoch      Epoch
 * @param alg        Revocation algorithm
 * @return True if valid
 */
public static boolean verifyEpochPK(PublicKey pk, Idemix.ECP2 epochPK, byte[] epochPkSig, long epoch, RevocationAlgorithm alg) throws CryptoException {
    Idemix.CredentialRevocationInformation.Builder builder = Idemix.CredentialRevocationInformation.newBuilder();
    builder.setRevocationAlg(alg.ordinal());
    builder.setEpochPk(epochPK);
    builder.setEpoch(epoch);
    Idemix.CredentialRevocationInformation cri = builder.build();
    byte[] bytesTosign = cri.toByteArray();
    try {
        Signature dsa = Signature.getInstance("SHA256withECDSA");
        dsa.initVerify(pk);
        dsa.update(bytesTosign);

        return dsa.verify(epochPkSig);
    } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
        throw new CryptoException("Error during the EpochPK verification", e);
    }
}
 
Example 4
Source File: ECSignerTest.java    From fusionauth-jwt with Apache License 2.0 6 votes vote down vote up
@Test
public void round_trip_raw1() throws Exception {
  // Generate a key-pair and sign and verify a message
  KeyPairGenerator g = KeyPairGenerator.getInstance("EC");
  ECGenParameterSpec parameterSpec = new ECGenParameterSpec("secp256r1");
  g.initialize(parameterSpec);
  KeyPair pair = g.generateKeyPair();

  // Instance of signature class with SHA256withECDSA algorithm
  Signature signature = Signature.getInstance("SHA256withECDSA");
  signature.initSign(pair.getPrivate());

  // Sign a message
  String message = "text ecdsa with sha256";
  signature.update((message).getBytes(StandardCharsets.UTF_8));
  byte[] signatureBytes = signature.sign();

  // Validation
  Signature verifier = Signature.getInstance("SHA256withECDSA");
  verifier.initVerify(pair.getPublic());
  verifier.update(message.getBytes(StandardCharsets.UTF_8));
  assertTrue(verifier.verify(signatureBytes));
}
 
Example 5
Source File: X509Cert.java    From xipki with Apache License 2.0 5 votes vote down vote up
public void verify(PublicKey key)
    throws SignatureException, InvalidKeyException, CertificateException,
    NoSuchAlgorithmException, NoSuchProviderException {
  if (jceInstance != null) {
    jceInstance.verify(key);
  } else {
    String sigName = AlgorithmUtil.getSignatureAlgoName(bcInstance.getSignatureAlgorithm());
    Signature signature = Signature.getInstance(sigName);
    checkBcSignature(key, signature);
  }
}
 
Example 6
Source File: Ecdsa.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
@Override
public byte[] sign(byte[] digest) throws GeneralSecurityException {
    checkDigestLength(digest);
	Signature signature = Signature.getInstance(ALGORITHM, _provider);
	signature.initSign(_keyPair.getPrivate());
	signature.update(digest);
	return SignatureEncoding.fromAsn1Der(signature.sign(), _algorithm);
}
 
Example 7
Source File: ECSignatureFactory.java    From asf-sdk with GNU General Public License v3.0 5 votes vote down vote up
public static Signature getRawInstance(Provider provider) {
  try {
    return Signature.getInstance(RAW_ALGORITHM, provider);
  } catch (NoSuchAlgorithmException ex) {
    throw new AssertionError(rawAlgorithmAssertionMsg, ex);
  }
}
 
Example 8
Source File: SignatureServiceImpl.java    From authlib-agent with MIT License 5 votes vote down vote up
@Override
public byte[] sign(byte[] data) throws GeneralSecurityException {
	if (key == null) {
		throw new InvalidKeyException("no key to sign with");
	}
	Signature signature = Signature.getInstance("SHA1withRSA");
	signature.initSign(key, getSecureRandom());
	signature.update(data);
	return signature.sign();
}
 
Example 9
Source File: SignatureDSA.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
    if (!(publicKey instanceof PublicKey)) {
        String supplied = publicKey.getClass().getName();
        String needed = PublicKey.class.getName();
        Object exArgs[] = { supplied, needed };

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

    try {
        this.signatureAlgorithm.initVerify((PublicKey) publicKey);
    } catch (InvalidKeyException ex) {
        // reinstantiate Signature object to work around bug in JDK
        // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
        Signature sig = this.signatureAlgorithm;
        try {
            this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
        } catch (Exception e) {
            // this shouldn't occur, but if it does, restore previous
            // Signature
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
            }
            this.signatureAlgorithm = sig;
        }
        throw new XMLSignatureException("empty", ex);
    }
    size = ((DSAKey)publicKey).getParams().getQ().bitLength();
}
 
Example 10
Source File: EncodingXMLTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testRSA() throws Exception {
	KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
	KeyPair pair = gen.generateKeyPair();

	Signature s = Signature.getInstance("SHA256withRSA");
	s.initSign(pair.getPrivate());
	s.update(HELLO_WORLD.getBytes());
	byte[] binary = s.sign();
	assertTrue(Arrays.equals(binary, DSSSignatureUtils.convertToXmlDSig(EncryptionAlgorithm.RSA, binary)));
}
 
Example 11
Source File: NonStandardNames.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example 12
Source File: Correctness.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String SIGALG = "SHA1withRSA";
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = kpg.generateKeyPair();

        SignedObject so1 = new SignedObject("Hello", kp.getPrivate(),
                Signature.getInstance(SIGALG));

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(so1);
        out.close();

        byte[] data = byteOut.toByteArray();

        SignedObject so2 = (SignedObject)new ObjectInputStream(
                new ByteArrayInputStream(data)).readObject();

        if (!so2.getObject().equals("Hello")) {
            throw new Exception("Content changed");
        }
        if (!so2.getAlgorithm().equals(SIGALG)) {
            throw new Exception("Signature algorithm unknown");
        }
        if (!so2.verify(kp.getPublic(), Signature.getInstance(SIGALG))) {
            throw new Exception("Not verified");
        }
    }
 
Example 13
Source File: AttestationProtocol.java    From AttestationServer with MIT License 5 votes vote down vote up
private static void verifySignature(final PublicKey key, final ByteBuffer message,
        final byte[] signature) throws GeneralSecurityException {
    final Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
    sig.initVerify(key);
    sig.update(message);
    if (!sig.verify(signature)) {
        throw new GeneralSecurityException("signature verification failed");
    }
}
 
Example 14
Source File: DMTokenizer.java    From GlobalPlatformPro with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected byte[] getToken(CommandAPDU apdu) {
    try {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initSign(privateKey);
        signer.update(dtbs(apdu));
        byte[] signature = signer.sign();
        logger.debug("Generated DM token: {}", HexUtils.bin2hex(signature));
        return signature;
    } catch (GeneralSecurityException e) {
        throw new GPException("Can not calculate DM token: " + e.getMessage(), e);
    }
}
 
Example 15
Source File: Main.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Generate a certificate: Read PKCS10 request from in, and print
 * certificate to out. Use alias as CA, sigAlgName as the signature
 * type.
 */
private void doGenCert(String alias, String sigAlgName, InputStream in, PrintStream out)
        throws Exception {


    Certificate signerCert = keyStore.getCertificate(alias);
    byte[] encoded = signerCert.getEncoded();
    X509CertImpl signerCertImpl = new X509CertImpl(encoded);
    X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get(
            X509CertImpl.NAME + "." + X509CertImpl.INFO);
    X500Name issuer = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "." +
                                       X509CertInfo.DN_NAME);

    Date firstDate = getStartDate(startDate);
    Date lastDate = new Date();
    lastDate.setTime(firstDate.getTime() + validity*1000L*24L*60L*60L);
    CertificateValidity interval = new CertificateValidity(firstDate,
                                                           lastDate);

    PrivateKey privateKey =
            (PrivateKey)recoverKey(alias, storePass, keyPass).fst;
    if (sigAlgName == null) {
        sigAlgName = getCompatibleSigAlgName(privateKey.getAlgorithm());
    }
    Signature signature = Signature.getInstance(sigAlgName);
    signature.initSign(privateKey);

    X509CertInfo info = new X509CertInfo();
    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
                new java.util.Random().nextInt() & 0x7fffffff));
    info.set(X509CertInfo.VERSION,
                new CertificateVersion(CertificateVersion.V3));
    info.set(X509CertInfo.ALGORITHM_ID,
                new CertificateAlgorithmId(
                    AlgorithmId.get(sigAlgName)));
    info.set(X509CertInfo.ISSUER, issuer);

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    boolean canRead = false;
    StringBuffer sb = new StringBuffer();
    while (true) {
        String s = reader.readLine();
        if (s == null) break;
        // OpenSSL does not use NEW
        //if (s.startsWith("-----BEGIN NEW CERTIFICATE REQUEST-----")) {
        if (s.startsWith("-----BEGIN") && s.indexOf("REQUEST") >= 0) {
            canRead = true;
        //} else if (s.startsWith("-----END NEW CERTIFICATE REQUEST-----")) {
        } else if (s.startsWith("-----END") && s.indexOf("REQUEST") >= 0) {
            break;
        } else if (canRead) {
            sb.append(s);
        }
    }
    byte[] rawReq = Base64.getMimeDecoder().decode(new String(sb));
    PKCS10 req = new PKCS10(rawReq);

    info.set(X509CertInfo.KEY, new CertificateX509Key(req.getSubjectPublicKeyInfo()));
    info.set(X509CertInfo.SUBJECT,
                dname==null?req.getSubjectName():new X500Name(dname));
    CertificateExtensions reqex = null;
    Iterator<PKCS10Attribute> attrs = req.getAttributes().getAttributes().iterator();
    while (attrs.hasNext()) {
        PKCS10Attribute attr = attrs.next();
        if (attr.getAttributeId().equals((Object)PKCS9Attribute.EXTENSION_REQUEST_OID)) {
            reqex = (CertificateExtensions)attr.getAttributeValue();
        }
    }
    CertificateExtensions ext = createV3Extensions(
            reqex,
            null,
            v3ext,
            req.getSubjectPublicKeyInfo(),
            signerCert.getPublicKey());
    info.set(X509CertInfo.EXTENSIONS, ext);
    X509CertImpl cert = new X509CertImpl(info);
    cert.sign(privateKey, sigAlgName);
    dumpCert(cert, out);
    for (Certificate ca: keyStore.getCertificateChain(alias)) {
        if (ca instanceof X509Certificate) {
            X509Certificate xca = (X509Certificate)ca;
            if (!isSelfSigned(xca)) {
                dumpCert(xca, out);
            }
        }
    }
}
 
Example 16
Source File: X509CRLImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Encodes an X.509 CRL, and signs it using the given key.
 *
 * @param key the private key used for signing.
 * @param algorithm the name of the signature algorithm used.
 * @param provider the name of the provider.
 *
 * @exception NoSuchAlgorithmException on unsupported signature
 * algorithms.
 * @exception InvalidKeyException on incorrect key.
 * @exception NoSuchProviderException on incorrect provider.
 * @exception SignatureException on signature errors.
 * @exception CRLException if any mandatory data was omitted.
 */
public void sign(PrivateKey key, String algorithm, String provider)
throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
    NoSuchProviderException, SignatureException {
    try {
        if (readOnly)
            throw new CRLException("cannot over-write existing CRL");
        Signature sigEngine = null;
        if ((provider == null) || (provider.length() == 0))
            sigEngine = Signature.getInstance(algorithm);
        else
            sigEngine = Signature.getInstance(algorithm, provider);

        sigEngine.initSign(key);

                            // in case the name is reset
        sigAlgId = AlgorithmId.get(sigEngine.getAlgorithm());
        infoSigAlgId = sigAlgId;

        DerOutputStream out = new DerOutputStream();
        DerOutputStream tmp = new DerOutputStream();

        // encode crl info
        encodeInfo(tmp);

        // encode algorithm identifier
        sigAlgId.encode(tmp);

        // Create and encode the signature itself.
        sigEngine.update(tbsCertList, 0, tbsCertList.length);
        signature = sigEngine.sign();
        tmp.putBitString(signature);

        // Wrap the signed data in a SEQUENCE { data, algorithm, sig }
        out.write(DerValue.tag_Sequence, tmp);
        signedCRL = out.toByteArray();
        readOnly = true;

    } catch (IOException e) {
        throw new CRLException("Error while encoding data: " +
                               e.getMessage());
    }
}
 
Example 17
Source File: Basic.java    From openjdk-8-source 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 18
Source File: Main.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Generate a certificate: Read PKCS10 request from in, and print
 * certificate to out. Use alias as CA, sigAlgName as the signature
 * type.
 */
private void doGenCert(String alias, String sigAlgName, InputStream in, PrintStream out)
        throws Exception {


    Certificate signerCert = keyStore.getCertificate(alias);
    byte[] encoded = signerCert.getEncoded();
    X509CertImpl signerCertImpl = new X509CertImpl(encoded);
    X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get(
            X509CertImpl.NAME + "." + X509CertImpl.INFO);
    X500Name issuer = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "." +
                                       X509CertInfo.DN_NAME);

    Date firstDate = getStartDate(startDate);
    Date lastDate = new Date();
    lastDate.setTime(firstDate.getTime() + validity*1000L*24L*60L*60L);
    CertificateValidity interval = new CertificateValidity(firstDate,
                                                           lastDate);

    PrivateKey privateKey =
            (PrivateKey)recoverKey(alias, storePass, keyPass).fst;
    if (sigAlgName == null) {
        sigAlgName = getCompatibleSigAlgName(privateKey.getAlgorithm());
    }
    Signature signature = Signature.getInstance(sigAlgName);
    signature.initSign(privateKey);

    X509CertInfo info = new X509CertInfo();
    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
                new java.util.Random().nextInt() & 0x7fffffff));
    info.set(X509CertInfo.VERSION,
                new CertificateVersion(CertificateVersion.V3));
    info.set(X509CertInfo.ALGORITHM_ID,
                new CertificateAlgorithmId(
                    AlgorithmId.get(sigAlgName)));
    info.set(X509CertInfo.ISSUER, issuer);

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    boolean canRead = false;
    StringBuffer sb = new StringBuffer();
    while (true) {
        String s = reader.readLine();
        if (s == null) break;
        // OpenSSL does not use NEW
        //if (s.startsWith("-----BEGIN NEW CERTIFICATE REQUEST-----")) {
        if (s.startsWith("-----BEGIN") && s.indexOf("REQUEST") >= 0) {
            canRead = true;
        //} else if (s.startsWith("-----END NEW CERTIFICATE REQUEST-----")) {
        } else if (s.startsWith("-----END") && s.indexOf("REQUEST") >= 0) {
            break;
        } else if (canRead) {
            sb.append(s);
        }
    }
    byte[] rawReq = Base64.getMimeDecoder().decode(new String(sb));
    PKCS10 req = new PKCS10(rawReq);

    info.set(X509CertInfo.KEY, new CertificateX509Key(req.getSubjectPublicKeyInfo()));
    info.set(X509CertInfo.SUBJECT,
                dname==null?req.getSubjectName():new X500Name(dname));
    CertificateExtensions reqex = null;
    Iterator<PKCS10Attribute> attrs = req.getAttributes().getAttributes().iterator();
    while (attrs.hasNext()) {
        PKCS10Attribute attr = attrs.next();
        if (attr.getAttributeId().equals((Object)PKCS9Attribute.EXTENSION_REQUEST_OID)) {
            reqex = (CertificateExtensions)attr.getAttributeValue();
        }
    }
    CertificateExtensions ext = createV3Extensions(
            reqex,
            null,
            v3ext,
            req.getSubjectPublicKeyInfo(),
            signerCert.getPublicKey());
    info.set(X509CertInfo.EXTENSIONS, ext);
    X509CertImpl cert = new X509CertImpl(info);
    cert.sign(privateKey, sigAlgName);
    dumpCert(cert, out);
    for (Certificate ca: keyStore.getCertificateChain(alias)) {
        if (ca instanceof X509Certificate) {
            X509Certificate xca = (X509Certificate)ca;
            if (!isSelfSigned(xca)) {
                dumpCert(xca, out);
            }
        }
    }
}
 
Example 19
Source File: CertSigner.java    From MaxKey with Apache License 2.0 3 votes vote down vote up
/**
 * <p>
 * 生成数据签名
 * </p>
 * 
 * @param data 源数�?
 * @param keyStorePath 密钥库存储路�?
 * @param alias x509Certificate alias
 * @param password 密钥库密�?
 * @return
 * @throws Exception
 */
public static byte[] sign(byte[] data, KeyStore keyStore, String alias, String password) throws Exception {
    // 获得证书
    X509Certificate x509Certificate = (X509Certificate) KeyStoreUtil.getCertificate(keyStore, alias, password);
    // 取得私钥
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
    // 构建签名
    Signature signature = Signature.getInstance(x509Certificate.getSigAlgName());
    signature.initSign(privateKey);
    signature.update(data);
    return signature.sign();
}
 
Example 20
Source File: CertSigner.java    From MaxKey with Apache License 2.0 3 votes vote down vote up
/**
 * <p>
 * 验证签名
 * </p>
 * 
 * @param data 已加密数�?
 * @param sign 数据签名[BASE64]
 * @param certificatePath 证书存储路径
 * @return
 * @throws Exception
 */
public static boolean verifySign(byte[] data, String sign, X509Certificate certificate) 
        throws Exception {
    // 获得公钥
    PublicKey publicKey = certificate.getPublicKey();
    // 构建签名
    Signature signature = Signature.getInstance(certificate.getSigAlgName());
    signature.initVerify(publicKey);
    signature.update(data);
    return signature.verify(HexUtils.hex2Bytes(sign));
}