类java.security.Signature源码实例Demo

下面列出了怎么用java.security.Signature的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: Jabit   文件: BouncyCryptography.java
@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);
    }
}
 
源代码2 项目: api   文件: Nacl.java
/**
 * 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;
    }
}
 
源代码3 项目: kogito-runtimes   文件: KeyStoreHelper.java
/**
 * 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 );
}
 
源代码4 项目: seed   文件: CodecUtil.java
/**
 * 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);
    }
}
 
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");
	}
}
 
源代码6 项目: cxf   文件: CryptoUtils.java
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);
    }
}
 
源代码7 项目: swim   文件: ReconSignature.java
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);
  }
}
 
源代码8 项目: xipki   文件: QaP11Actions.java
@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;
}
 
源代码9 项目: aes-rsa-java   文件: RSA.java
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;
}
 
源代码10 项目: RipplePower   文件: X509CertificateObject.java
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");
    }
}
 
源代码11 项目: openjdk-jdk8u-backup   文件: Offsets.java
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);
}
 
源代码12 项目: dss   文件: EncodingXMLTest.java
@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)));
}
 
源代码13 项目: TencentKona-8   文件: NonStandardNames.java
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");
        }
    }
 
源代码14 项目: james-project   文件: JamesSignatureHandler.java
@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);
    }
}
 
源代码15 项目: pay-spring-boot   文件: AbstractAli.java
/**
 * 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);
    }
}
 
源代码16 项目: factura-electronica   文件: TFDv1c32.java
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);
}
 
源代码17 项目: jdk8u-jdk   文件: SignatureECDSA.java
/** @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);
    }
}
 
源代码18 项目: openjdk-jdk9   文件: Offsets.java
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);
}
 
源代码19 项目: UAF   文件: ExampleFidoUafActivity.java
@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);
}
 
源代码20 项目: openjdk-8   文件: SolarisShortDSA.java
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);
}
 
源代码21 项目: openjdk-jdk8u   文件: InteropWithSunRsaSign.java
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);
}
 
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;
}
 
源代码23 项目: jdk8u_jdk   文件: TestSignatureOidHelper.java
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");
    }
}
 
源代码24 项目: TencentKona-8   文件: X509CRLImpl.java
/**
 * 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;
}
 
源代码25 项目: openjdk-8   文件: X509CRLImpl.java
/**
 * 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;
}
 
源代码26 项目: factura-electronica   文件: TFDv1.java
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
}
 
源代码27 项目: jeesuite-libs   文件: RsaSignUtils.java
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;
	}

}
 
源代码28 项目: Auditor   文件: AttestationProtocol.java
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");
    }
}
 
源代码29 项目: fabric-sdk-java   文件: RevocationAuthority.java
/**
 * 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");
    }
}
 
源代码30 项目: webauthn4j   文件: JWSFactory.java
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);
    }
}
 
 类所在包
 同包方法