Java Code Examples for java.security.Signature

The following examples show how to use java.security.Signature. These examples are extracted from open source projects. 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 Project: Jabit   Source File: BouncyCryptography.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] getSignature(byte[] data, PrivateKey privateKey) {
    try {
        ECParameterSpec spec = new ECParameterSpec(
            EC_CURVE_PARAMETERS.getCurve(),
            EC_CURVE_PARAMETERS.getG(),
            EC_CURVE_PARAMETERS.getN(),
            EC_CURVE_PARAMETERS.getH(),
            EC_CURVE_PARAMETERS.getSeed()
        );

        BigInteger d = keyToBigInt(privateKey.getPrivateSigningKey());
        KeySpec keySpec = new ECPrivateKeySpec(d, spec);
        java.security.PrivateKey privKey = KeyFactory.getInstance(ALGORITHM_ECDSA, provider)
            .generatePrivate(keySpec);

        Signature sig = Signature.getInstance(ALGORITHM_ECDSA, provider);
        sig.initSign(privKey);
        sig.update(data);
        return sig.sign();
    } catch (GeneralSecurityException e) {
        throw new ApplicationException(e);
    }
}
 
Example 2
Source Project: api   Source File: Nacl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Signs a message using the supplied secretKey
 * Returns message signature of `message`, using the `secretKey`.
 * **example**  
 * 
 * ```java
 * naclSign([...], [...]); // => [...]
 * ```
 */
//export default function naclSign (message: Uint8Array, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
//    assert(secretKey, 'Expected valid secretKey');
//
//    return isReady()
//            ? ed25519Sign(publicKey as Uint8Array, (secretKey as Uint8Array).subarray(0, 32), message)
//: nacl.sign.detached(message, secretKey as Uint8Array);
//}
public static byte[] naclSign(byte[] message, final Types.Keypair keypair) {
    try {
        EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.ED_25519);
        Signature sgr = new EdDSAEngine(MessageDigest.getInstance(spec.getHashAlgorithm()));

        EdDSAPrivateKeySpec edPrivateKey = new EdDSAPrivateKeySpec(spec, keypair.secretKey);
        PrivateKey privateKey = new EdDSAPrivateKey(edPrivateKey);
        sgr.initSign(privateKey);
        sgr.update(message);
        return sgr.sign();
    }
    catch (Exception e) {
        return null;
    }
}
 
Example 3
Source Project: kogito-runtimes   Source File: KeyStoreHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks the given byte[] data against the signature, using the
 * public key with which this helper was initialised and the algorithm
 * MD5 with RSA.
 *
 * @param data the original data that was signed
 * @param signature the provided signature
 *
 * @return true in case the signature matches, false otherwise.
 *
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public boolean checkDataWithPublicKey(final String publicKeyAlias,
                                      final byte[] data,
                                      final byte[] signature) throws KeyStoreException,
                                                             NoSuchAlgorithmException,
                                                             InvalidKeyException,
                                                             SignatureException {
    if( pubKeyStore == null ) {
        throw new RuntimeException( "Key store with public key not configured. Please configure it properly before using signed serialization." );
    }
    Certificate cert = pubKeyStore.getCertificate( publicKeyAlias );
    if( cert == null ) {
        throw new RuntimeException( "Public certificate for key '"+publicKeyAlias+"' not found in the configured key store. Impossible to deserialize the object." );
    }
    Signature sig = Signature.getInstance( "MD5withRSA" );
    sig.initVerify( cert.getPublicKey() );
    sig.update( data );
    return sig.verify( signature );
}
 
Example 4
Source Project: seed   Source File: CodecUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * RSA算法使用私钥对数据生成数字签名
 * 注意签名算法SHA1WithRSA已被废弃,推荐使用SHA256WithRSA
 * @param data 待签名的明文字符串
 * @param key  RSA私钥字符串
 * @return RSA私钥签名后的经过Base64编码的字符串
 */
public static String buildRSASignByPrivateKey(String data, String key){
    try{
        //通过PKCS#8编码的Key指令获得私钥对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        //sign
        Signature signature = Signature.getInstance(ALGORITHM_RSA_SIGN);
        signature.initSign(privateKey);
        signature.update(data.getBytes(SeedConstants.DEFAULT_CHARSET));
        return Base64.encodeBase64URLSafeString(signature.sign());
    }catch(Exception e){
        throw new RuntimeException("签名字符串[" + data + "]时遇到异常", e);
    }
}
 
Example 5
public void verificar() throws Exception {
	String certStr = document.getCertificado();
	Base64 b64 = new Base64();
	byte[] cbs = b64.decode(certStr);

	X509Certificate cert = KeyLoaderFactory.createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER,new ByteArrayInputStream(cbs)).getKey();

	String sigStr = document.getSello();
	byte[] signature = b64.decode(sigStr); 
	byte[] bytes = getOriginalBytes();
	Signature sig = Signature.getInstance("SHA1withRSA");
	sig.initVerify(cert);
	sig.update(bytes);
	boolean bool = sig.verify(signature);
	if (!bool) {
		throw new Exception("Invalid signature");
	}
}
 
Example 6
Source Project: cxf   Source File: CryptoUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Signature getSignature(PrivateKey key, String signAlgo, SecureRandom random,
                              AlgorithmParameterSpec params) {
    try {
        Signature s = Signature.getInstance(signAlgo);
        if (random == null) {
            s.initSign(key);
        } else {
            s.initSign(key, random);
        }
        if (params != null) {
            s.setParameter(params);
        }
        return s;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example 7
Source Project: swim   Source File: ReconSignature.java    License: Apache License 2.0 6 votes vote down vote up
public static ReconSignature signRsa(Signature signature, PrivateKey privateKey,
                                     Value payload, Value protectedHeader,
                                     Value unprotectedHeader) {
  final Output<Data> output = Data.output();
  Recon.structureWriter().writeValue(payload, output);
  Recon.structureWriter().writeAttr(Text.from("protected"), protectedHeader, output);
  final Data signingInput = output.bind();

  try {
    signature.initSign(privateKey);
    signature.update(signingInput.asByteBuffer());
    final Data hash = Data.wrap(signature.sign());
    final Value signatureHeader;
    if (unprotectedHeader.isDefined()) {
      signatureHeader = unprotectedHeader.concat(Slot.of("hash", hash));
    } else {
      signatureHeader = Record.of(Slot.of("hash", hash));
    }
    return new ReconSignature(payload, protectedHeader, signatureHeader);
  } catch (GeneralSecurityException cause) {
    throw new RuntimeException(cause);
  }
}
 
Example 8
Source Project: xipki   Source File: QaP11Actions.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Object execute1(PrivateKey key, Certificate cert) throws Exception {
  PublicKey pubKey = cert.getPublicKey();

  String sigAlgo = getSignatureAlgo(pubKey);
  println("signature algorithm: " + sigAlgo);
  Signature sig = Signature.getInstance(sigAlgo);
  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");
  ver.initVerify(pubKey);
  ver.update(data);
  boolean valid = ver.verify(signature);
  println("signature valid: " + valid);
  return null;
}
 
Example 9
Source Project: aes-rsa-java   Source File: RSA.java    License: Apache License 2.0 6 votes vote down vote up
public static String sign(String content, String privateKey) {
	String charset = ConfigureEncryptAndDecrypt.CHAR_ENCODING;
	try {
		PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
				Base64.decodeBase64(privateKey.getBytes()));
		KeyFactory keyf = KeyFactory.getInstance("RSA");
		PrivateKey priKey = keyf.generatePrivate(priPKCS8);

		Signature signature = Signature.getInstance("SHA256WithRSA");

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

		byte[] signed = signature.sign();

		return new String(Base64.encodeBase64(signed));
	} catch (Exception e) {

	}

	return null;
}
 
Example 10
Source Project: RipplePower   Source File: X509CertificateObject.java    License: Apache License 2.0 6 votes vote down vote up
private void checkSignature(
    PublicKey key, 
    Signature signature) 
    throws CertificateException, NoSuchAlgorithmException, 
        SignatureException, InvalidKeyException
{
    if (!isAlgIdEqual(c.getSignatureAlgorithm(), c.getTBSCertificate().getSignature()))
    {
        throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
    }

    ASN1Encodable params = c.getSignatureAlgorithm().getParameters();

    // TODO This should go after the initVerify?
    X509SignatureUtil.setSignatureParameters(signature, params);

    signature.initVerify(key);

    signature.update(this.getTBSCertificate());

    if (!signature.verify(this.getSignature()))
    {
        throw new SignatureException("certificate does not verify with supplied key");
    }
}
 
Example 11
Source Project: openjdk-jdk8u-backup   Source File: Offsets.java    License: GNU General Public License v2.0 5 votes vote down vote up
static Offsets init(String provider, String algorithm)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, SignatureException {
    // fill the cleartext data with random bytes
    byte[] cleartext = new byte[100];
    RandomFactory.getRandom().nextBytes(cleartext);

    // NONEwith requires input to be of 20 bytes
    int size = algorithm.contains("NONEwith") ? 20 : 100;

    // create signature instance
    Signature signature = Signature.getInstance(algorithm, provider);

    String keyAlgo;
    int keySize = 2048;
    if (algorithm.contains("RSA")) {
        keyAlgo = "RSA";
    } else if (algorithm.contains("ECDSA")) {
        keyAlgo = "EC";
        keySize = 256;
    } else if (algorithm.contains("DSA")) {
        keyAlgo = "DSA";
        if (algorithm.startsWith("SHAwith") ||
                algorithm.startsWith("SHA1with")) {
            keySize = 1024;
        }
    } else {
        throw new RuntimeException("Test doesn't support this signature "
                + "algorithm: " + algorithm);
    }

    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo, provider);
    kpg.initialize(keySize);
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubkey = kp.getPublic();
    PrivateKey privkey = kp.getPrivate();

    return new Offsets(signature, pubkey, privkey, size, cleartext);
}
 
Example 12
Source Project: dss   Source File: EncodingXMLTest.java    License: 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 13
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 14
Source Project: james-project   Source File: JamesSignatureHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String sign(String source) {
    Preconditions.checkNotNull(source);
    try {
        Signature javaSignature = Signature.getInstance(ALGORITHM);
        javaSignature.initSign(securityKeys.getPrivateKey());
        javaSignature.update(source.getBytes());
        return Base64.getEncoder().encodeToString(javaSignature.sign());
    } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source Project: pay-spring-boot   Source File: AbstractAli.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * RSA2签名
 * @param content 待签名字符串
 * @return 签名
 */
protected String signRSA2(String content) {
    try {
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(PRIVATE_KEY);
        signature.update(content.getBytes(CommonConfig.UNIFY_CHARSET));
        byte[] bytes = signature.sign();

        return PayBase64.encode(bytes);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
Source Project: factura-electronica   Source File: TFDv1c32.java    License: Apache License 2.0 5 votes vote down vote up
String getSignature(PrivateKey key) throws Exception {
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);
    sig.update(bytes);
    byte[] signed = sig.sign();
    Base64 b64 = new Base64(-1);
    return b64.encodeToString(signed);
}
 
Example 17
Source Project: jdk8u-jdk   Source File: SignatureECDSA.java    License: 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);
    }
}
 
Example 18
Source Project: openjdk-jdk9   Source File: Offsets.java    License: GNU General Public License v2.0 5 votes vote down vote up
static Offsets init(String provider, String algorithm)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, SignatureException {
    // fill the cleartext data with random bytes
    byte[] cleartext = new byte[100];
    RandomFactory.getRandom().nextBytes(cleartext);

    // NONEwith requires input to be of 20 bytes
    int size = algorithm.contains("NONEwith") ? 20 : 100;

    // create signature instance
    Signature signature = Signature.getInstance(algorithm, provider);

    String keyAlgo;
    if (algorithm.contains("RSA")) {
        keyAlgo = "RSA";
    } else if (algorithm.contains("ECDSA")) {
        keyAlgo = "EC";
    } else if (algorithm.contains("DSA")) {
        keyAlgo = "DSA";
    } else {
        throw new RuntimeException("Test doesn't support this signature "
                + "algorithm: " + algorithm);
    }

    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo, provider);
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubkey = kp.getPublic();
    PrivateKey privkey = kp.getPrivate();

    return new Offsets(signature, pubkey, privkey, size, cleartext);
}
 
Example 19
Source Project: UAF   Source File: ExampleFidoUafActivity.java    License: Apache License 2.0 5 votes vote down vote up
@NonNull
private FidoSigner createFidoSigner() throws NoSuchAlgorithmException, InvalidKeyException {
    Signature signature = Signature.getInstance("SHA256withECDSA");
    PrivateKey privateKey = fidoKeystore.getKeyPair(Preferences.getSettingsParam("username")).getPrivate();
    signature.initSign(privateKey);

    return new FidoSignerAndroidM(signature);
}
 
Example 20
Source Project: openjdk-8   Source File: SolarisShortDSA.java    License: GNU General Public License v2.0 5 votes vote down vote up
static boolean use(KeyPair kp) throws Exception {
     Signature sig = Signature.getInstance("SHA1withDSA");
     sig.initSign(kp.getPrivate());
     sig.update(data);
     byte[] signed = sig.sign();
     Signature sig2 = Signature.getInstance("SHA1withDSA");
     sig2.initVerify(kp.getPublic());
     sig2.update(data);
     return sig2.verify(signed);
}
 
Example 21
static boolean test(String pg, String ps, String pv, PSSParameterSpec pss)
        throws Exception {

    KeyPairGenerator kpg = pg.length() == 1
            ? KeyPairGenerator.getInstance("RSA")
            :KeyPairGenerator.getInstance("RSA", pg);
    kpg.initialize(
            pss.getDigestAlgorithm().equals("SHA-512") ? 2048: 1024,
            NOT_SECURE_RANDOM);
    KeyPair kp = kpg.generateKeyPair();
    PrivateKey pr = kp.getPrivate();
    PublicKey pu = kp.getPublic();

    Signature s = ps.length() == 1
            ? Signature.getInstance("RSASSA-PSS")
            : Signature.getInstance("RSASSA-PSS", ps);
    s.initSign(pr);
    s.setParameter(pss);
    s.update(msg);
    byte[] sig = s.sign();

    Signature s2 = pv.length() == 1
            ? Signature.getInstance("RSASSA-PSS")
            : Signature.getInstance("RSASSA-PSS", pv);
    s2.initVerify(pu);
    s2.setParameter(pss);
    s2.update(msg);

    return s2.verify(sig);
}
 
Example 22
public boolean verifyTokenAsymmetric(OzoneBlockTokenIdentifier tokenId,
    byte[] signature, Certificate certificate) throws InvalidKeyException,
    NoSuchAlgorithmException, SignatureException {
  Signature rsaSignature = Signature.getInstance("SHA256withRSA");
  rsaSignature.initVerify(certificate);
  rsaSignature.update(tokenId.getBytes());
  boolean isValid = rsaSignature.verify(signature);
  return isValid;
}
 
Example 23
private void runTest(OidAlgorithmPair oidAlgorithmPair, KeyPair keyPair)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, SignatureException {
    Signature sgAlgorithm =
            Signature.getInstance(oidAlgorithmPair.algorithm, provider);
    Signature sgOid = Signature.getInstance(oidAlgorithmPair.oid, provider);

    if (sgAlgorithm == null) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance failed.%n",
                oidAlgorithmPair.algorithm));
    }

    if (sgOid == null) {
        throw new RuntimeException(
                String.format("Test failed: OID %s getInstance failed.%n",
                        oidAlgorithmPair.oid));
    }

    if (!sgAlgorithm.getAlgorithm().equals(oidAlgorithmPair.algorithm)) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance "
                        + "doesn't generate expected algorithm.%n",
                oidAlgorithmPair.algorithm));
    }

    sgAlgorithm.initSign(keyPair.getPrivate());
    sgAlgorithm.update(INPUT);
    sgOid.initVerify(keyPair.getPublic());
    sgOid.update(INPUT);
    if (!sgOid.verify(sgAlgorithm.sign())) {
        throw new RuntimeException(
                "Signature verification failed unexpectedly");
    }
}
 
Example 24
Source Project: TencentKona-8   Source File: X509CRLImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies that this CRL was signed using the
 * private key that corresponds to the given public key,
 * and that the signature verification was computed by
 * the given provider. Note that the specified Provider object
 * does not have to be registered in the provider list.
 *
 * @param key the PublicKey used to carry out the verification.
 * @param sigProvider the signature provider.
 *
 * @exception NoSuchAlgorithmException on unsupported signature
 * algorithms.
 * @exception InvalidKeyException on incorrect key.
 * @exception SignatureException on signature errors.
 * @exception CRLException on encoding errors.
 */
public synchronized void verify(PublicKey key, Provider sigProvider)
        throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
        SignatureException {

    if (signedCRL == null) {
        throw new CRLException("Uninitialized CRL");
    }
    Signature sigVerf = null;
    if (sigProvider == null) {
        sigVerf = Signature.getInstance(sigAlgId.getName());
    } else {
        sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider);
    }
    sigVerf.initVerify(key);

    if (tbsCertList == null) {
        throw new CRLException("Uninitialized CRL");
    }

    sigVerf.update(tbsCertList, 0, tbsCertList.length);

    if (!sigVerf.verify(signature)) {
        throw new SignatureException("Signature does not match.");
    }
    verifiedPublicKey = key;
}
 
Example 25
Source Project: openjdk-8   Source File: X509CRLImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies that this CRL was signed using the
 * private key that corresponds to the given public key,
 * and that the signature verification was computed by
 * the given provider. Note that the specified Provider object
 * does not have to be registered in the provider list.
 *
 * @param key the PublicKey used to carry out the verification.
 * @param sigProvider the signature provider.
 *
 * @exception NoSuchAlgorithmException on unsupported signature
 * algorithms.
 * @exception InvalidKeyException on incorrect key.
 * @exception SignatureException on signature errors.
 * @exception CRLException on encoding errors.
 */
public synchronized void verify(PublicKey key, Provider sigProvider)
        throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
        SignatureException {

    if (signedCRL == null) {
        throw new CRLException("Uninitialized CRL");
    }
    Signature sigVerf = null;
    if (sigProvider == null) {
        sigVerf = Signature.getInstance(sigAlgId.getName());
    } else {
        sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider);
    }
    sigVerf.initVerify(key);

    if (tbsCertList == null) {
        throw new CRLException("Uninitialized CRL");
    }

    sigVerf.update(tbsCertList, 0, tbsCertList.length);

    if (!sigVerf.verify(signature)) {
        throw new SignatureException("Signature does not match.");
    }
    verifiedPublicKey = key;
}
 
Example 26
Source Project: factura-electronica   Source File: TFDv1.java    License: Apache License 2.0 5 votes vote down vote up
public int verificar() throws Exception {
    if (tfd == null) {
        return 601; //No contiene timbrado
    }
    Base64 b64 = new Base64();
    String sigStr = tfd.getSelloSAT();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);
    boolean verified = sig.verify(signature);
    return verified ? 600 : 602; //Sello del timbrado no valido
}
 
Example 27
Source Project: jeesuite-libs   Source File: RsaSignUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean verifySignature(String contents, String sign, PublicKey publicKey) {
	try {
		byte[] data = contents.getBytes(StandardCharsets.UTF_8.name());
		byte[] dataSignature = Base64.decode(sign);

		Signature signature = Signature.getInstance(SIGN_ALGORITHM);
		signature.initVerify(publicKey);
		signature.update(data, 0, data.length);
		return signature.verify(dataSignature);
	} catch (Exception e) {
		return false;
	}

}
 
Example 28
Source Project: Auditor   Source File: AttestationProtocol.java    License: 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 29
Source Project: fabric-sdk-java   Source File: RevocationAuthority.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Credential Revocation Information object
 *
 * @param key              Private key
 * @param unrevokedHandles Array of unrevoked revocation handles
 * @param epoch            The counter (representing a time window) in which this CRI is valid
 * @param alg              Revocation algorithm
 * @return CredentialRevocationInformation object
 */
public static Idemix.CredentialRevocationInformation createCRI(PrivateKey key, BIG[] unrevokedHandles, int epoch, RevocationAlgorithm alg) throws CryptoException {
    Idemix.CredentialRevocationInformation.Builder builder = Idemix.CredentialRevocationInformation.newBuilder();
    builder.setRevocationAlg(alg.ordinal());
    builder.setEpoch(epoch);

    // Create epoch key
    WeakBB.KeyPair keyPair = WeakBB.weakBBKeyGen();
    if (alg == RevocationAlgorithm.ALG_NO_REVOCATION) {
        // Dummy PK in the proto
        builder.setEpochPk(IdemixUtils.transformToProto(IdemixUtils.genG2));
    } else {
        // Real PK only if we are going to use it
        builder.setEpochPk(IdemixUtils.transformToProto(keyPair.getPk()));
    }

    // Sign epoch + epoch key with the long term key
    byte[] signed;
    try {
        Idemix.CredentialRevocationInformation cri = builder.build();
        Signature ecdsa = Signature.getInstance("SHA256withECDSA");
        ecdsa.initSign(key);
        ecdsa.update(cri.toByteArray());
        signed = ecdsa.sign();

        builder.setEpochPkSig(ByteString.copyFrom(signed));
    } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
        throw new CryptoException("Error processing the signature");
    }

    if (alg == RevocationAlgorithm.ALG_NO_REVOCATION) {
        // build and return the credential information object
        return builder.build();
    } else {
        // If alg not supported, return null
        throw new IllegalArgumentException("Algorithm " + alg.name() + " not supported");
    }
}
 
Example 30
Source Project: webauthn4j   Source File: JWSFactory.java    License: Apache License 2.0 5 votes vote down vote up
public <T extends Serializable> JWS<T> create(JWSHeader header, T payload, PrivateKey privateKey) {
    String headerString = Base64UrlUtil.encodeToString(jsonConverter.writeValueAsString(header).getBytes(StandardCharsets.UTF_8));
    String payloadString = Base64UrlUtil.encodeToString(jsonConverter.writeValueAsString(payload).getBytes(StandardCharsets.UTF_8));
    String signedData = headerString + "." + payloadString;
    Signature signatureObj = SignatureUtil.createSignature(header.getAlg().getJcaName());
    try {
        signatureObj.initSign(privateKey);
        signatureObj.update(signedData.getBytes());
        byte[] derSignature = signatureObj.sign();
        byte[] jwsSignature = JWSSignatureUtil.convertDerSignatureToJwsSignature(derSignature);
        return new JWS<>(header, headerString, payload, payloadString, jwsSignature);
    } catch (InvalidKeyException | SignatureException e) {
        throw new IllegalArgumentException(e);
    }
}