/** * Given a piece of text and a message signature encoded in base64, returns an ECKey * containing the public key that was used to sign it. This can then be compared to the expected public key to * determine if the signature was correct. * * @param messageHash a piece of human readable text that was signed * @param signatureBase64 The Ethereum-format message signature in base64 * * @return - * @throws SignatureException If the public key could not be recovered or if there was a signature format error. */ public static byte[] signatureToKeyBytes(byte[] messageHash, String signatureBase64) throws SignatureException { byte[] signatureEncoded; try { signatureEncoded = Base64.decode(signatureBase64); } catch (RuntimeException e) { // This is what you get back from Bouncy Castle if base64 doesn't decode :( throw new SignatureException("Could not decode base64", e); } // Parse the signature bytes into r/s and the selector value. if (signatureEncoded.length < 65) throw new SignatureException("Signature truncated, expected 65 bytes and got " + signatureEncoded.length); return signatureToKeyBytes( messageHash, ECDSASignature.fromComponents( Arrays.copyOfRange(signatureEncoded, 1, 33), Arrays.copyOfRange(signatureEncoded, 33, 65), (byte) (signatureEncoded[0] & 0xFF))); }
/** * if has performance problem ,change Signature to ThreadLocal instance */ public static String sign(String content, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException { Signature signature = Signature.getInstance(SIGN_ALG); signature.initSign(privateKey); signature.update(content.getBytes()); byte[] signByte = signature.sign(); return encoder.encodeToString(signByte); }
/** * Returns the signature bytes of all the data * updated so far. * The format of the signature depends on the underlying * signature scheme. * * @return the signature bytes of the signing operation's result. * * @exception SignatureException if the engine is not * initialized properly or if this signature algorithm is unable to * process the input data provided. */ protected byte[] engineSign() throws SignatureException { byte[] hash = getDigestValue(); // Omit the hash OID when generating a Raw signature boolean noHashOID = this instanceof Raw; // Sign hash using MS Crypto APIs byte[] result = signHash(noHashOID, hash, hash.length, messageDigestAlgorithm, privateKey.getHCryptProvider(), privateKey.getHCryptKey()); // Convert signature array from little endian to big endian return convertEndianArray(result); }
protected boolean engineVerify( byte[] sigBytes) throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); BigInteger[] sig; try { sig = derDecode(sigBytes); } catch (Exception e) { throw new SignatureException("error decoding signature bytes."); } return signer.verifySignature(hash, sig[0], sig[1]); }
static byte[] calculateSignature( DERObjectIdentifier sigOid, String sigName, PrivateKey key, SecureRandom random, ASN1Encodable object) throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { Signature sig; if (sigOid == null) { throw new IllegalStateException("no signature algorithm specified"); } sig = X509Util.getSignatureInstance(sigName); if (random != null) { sig.initSign(key, random); } else { sig.initSign(key); } sig.update(object.toASN1Primitive().getEncoded(ASN1Encoding.DER)); return sig.sign(); }
/** * 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. * * @param key the PublicKey used to carry out the verification. * @param sigProvider the name of the signature provider. * * @exception NoSuchAlgorithmException on unsupported signature * algorithms. * @exception InvalidKeyException on incorrect key. * @exception NoSuchProviderException on incorrect provider. * @exception SignatureException on signature errors. * @exception CRLException on encoding errors. */ public synchronized void verify(PublicKey key, String sigProvider) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { if (sigProvider == null) { sigProvider = ""; } if ((verifiedPublicKey != null) && verifiedPublicKey.equals(key)) { // this CRL has already been successfully verified using // this public key. Make sure providers match, too. if (sigProvider.equals(verifiedProvider)) { return; } } if (signedCRL == null) { throw new CRLException("Uninitialized CRL"); } Signature sigVerf = null; if (sigProvider.length() == 0) { 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; verifiedProvider = sigProvider; }
public final void verify( PublicKey key, String provider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { Signature signature = null; if (!cert.getSignatureAlgorithm().equals(cert.getAcinfo().getSignature())) { throw new CertificateException("Signature algorithm in certificate info not same as outer certificate"); } signature = Signature.getInstance(cert.getSignatureAlgorithm().getObjectId().getId(), provider); signature.initVerify(key); try { signature.update(cert.getAcinfo().getEncoded()); } catch (IOException e) { throw new SignatureException("Exception encoding certificate info object"); } if (!signature.verify(this.getSignature())) { throw new InvalidKeyException("Public key presented not for certificate signature"); } }
/** * 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; }
/** * Verifies that the given certificate was signed using the private key that corresponds to the * public key of the provided certificate. * * @param certificate The X509Certificate which is to be checked * @param issuingCertificate The X.509 certificate which holds the public key corresponding to the private * key with which the given certificate should have been signed * @return True, if the verification was successful, false otherwise */ public static boolean verifySignature(X509Certificate certificate, X509Certificate issuingCertificate) { X500Principal subject = certificate.getSubjectX500Principal(); X500Principal expectedIssuerSubject = certificate.getIssuerX500Principal(); X500Principal issuerSubject = issuingCertificate.getSubjectX500Principal(); PublicKey publicKeyForSignature = issuingCertificate.getPublicKey(); try { certificate.verify(publicKeyForSignature); return true; } catch (InvalidKeyException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException e) { getLogger().warn("\n" + "\tSignature verification of certificate having distinguished name \n" + "\t'" + subject.getName() + "'\n" + "\twith certificate having distinguished name (the issuer) \n" + "\t'" + issuerSubject.getName() + "'\n" + "\tfailed. Expected issuer has distinguished name \n" + "\t'" + expectedIssuerSubject.getName() + "' (" + e.getClass().getSimpleName() + ")", e); } return false; }
public static byte[] signatureToKeyBytes(byte[] messageHash, ECDSASignature sig) throws SignatureException { check(messageHash.length == 32, "messageHash argument has length " + messageHash.length); int header = sig.v; // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, // 0x1D = second key with even y, 0x1E = second key with odd y if (header < 27 || header > 34) throw new SignatureException("Header byte out of range: " + header); if (header >= 31) { header -= 4; } int recId = header - 27; byte[] key = ECKey.recoverPubBytesFromSignature(recId, sig, messageHash); if (key == null) throw new SignatureException("Could not recover public key from signature"); return key; }
public final void verify( PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { Signature signature; String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); try { signature = Signature.getInstance(sigName, BouncyCastleProvider.PROVIDER_NAME); } catch (Exception e) { signature = Signature.getInstance(sigName); } checkSignature(key, signature); }
/** * Computes RFC 2104-compliant HMAC signature. * * @param data * The data to be signed. * @param key * The signing key. * @return * The Base64-encoded RFC 2104-compliant HMAC signature. * @throws * SignatureException when signature generation fails */ private static String calculateRFC2104HMAC(String data, String key) throws SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac result = EncodeBase64(rawHmac); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
public void verify(PublicKey key, String sigProvider) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { if (!c.getSignatureAlgorithm().equals(c.getTBSCertList().getSignature())) { throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList."); } Signature sig; if (sigProvider != null) { sig = Signature.getInstance(getSigAlgName(), sigProvider); } else { sig = Signature.getInstance(getSigAlgName()); } sig.initVerify(key); sig.update(this.getTBSCertList()); if (!sig.verify(this.getSignature())) { throw new SignatureException("CRL does not verify with supplied public key."); } }
/** * Sign byte-strings using the private key derived from the provided <em>seed</em>. * * @param seedBytes A <em>seed</em> to create a private key. Not the actual private key. The * seed will be transformed and expanded into an Ed25519 private key as described in <a * href="https://tools.ietf.org/html/rfc8032#page-13">RFC 8032</a>. */ public Signer(byte[] seedBytes) throws InvalidKeyException, SignatureException { checkArgument(seedBytes.length >= MIN_SEED_LENGTH, "insufficient private key seed length"); EdDSAPrivateKeySpec privateSpec = new EdDSAPrivateKeySpec(seedBytes, ED25519_SPEC); this.privateKey = new EdDSAPrivateKey(privateSpec); this.signer = new EdDSAEngine(RtHashing.newSha512()); signer.initSign(privateKey); }
/** @inheritDoc */ protected void engineUpdate(byte[] input) throws XMLSignatureException { try { this.signatureAlgorithm.update(input); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } }
public boolean valid(String token) { try { RSAAuthenticationToken rsaToken = RSAAuthenticationToken.fromStr(token); if (null == rsaToken) { LOGGER.error("token format is error, perhaps you need to set auth handler at consumer"); return false; } if (tokenExprired(rsaToken)) { LOGGER.error("token is expired"); return false; } if (validatedToken.contains(rsaToken)) { LOGGER.info("found vaildate token in vaildate pool"); return true; } String sign = rsaToken.getSign(); String content = rsaToken.plainToken(); String publicKey = getPublicKey(rsaToken.getInstanceId(), rsaToken.getServiceId()); boolean verify = RSAUtils.verify(publicKey, sign, content); if (verify && !tokenExprired(rsaToken)) { validatedToken.add(rsaToken); return true; } LOGGER.error("token verify error"); return false; } catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | SignatureException e) { LOGGER.error("verfiy error", e); return false; } }
protected void engineUpdate( byte[] b, int off, int len) throws SignatureException { pss.update(b, off, len); }
/** * Given an arbitrary piece of text and a Bitcoin-format message signature encoded in base64, returns an ECKey * containing the public key that was used to sign it. This can then be compared to the expected public key to * determine if the signature was correct. These sorts of signatures are compatible with the Bitcoin-Qt/bitcoind * format generated by signmessage/verifymessage RPCs and GUI menu options. They are intended for humans to verify * their communications with each other, hence the base64 format and the fact that the input is text. * * @param message Some piece of human readable text. * @param signatureBase64 The Bitcoin-format message signature in base64 * @throws SignatureException If the public key could not be recovered or if there was a signature format error. */ public static BtcECKey signedMessageToKey(String message, String signatureBase64) throws SignatureException { byte[] signatureEncoded; try { signatureEncoded = Base64.decode(signatureBase64); } catch (RuntimeException e) { // This is what you get back from Bouncy Castle if base64 doesn't decode :( throw new SignatureException("Could not decode base64", e); } // Parse the signature bytes into r/s and the selector value. if (signatureEncoded.length < 65) throw new SignatureException("Signature truncated, expected 65 bytes and got " + signatureEncoded.length); int header = signatureEncoded[0] & 0xFF; // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, // 0x1D = second key with even y, 0x1E = second key with odd y if (header < 27 || header > 34) throw new SignatureException("Header byte out of range: " + header); BigInteger r = new BigInteger(1, Arrays.copyOfRange(signatureEncoded, 1, 33)); BigInteger s = new BigInteger(1, Arrays.copyOfRange(signatureEncoded, 33, 65)); ECDSASignature sig = new ECDSASignature(r, s); byte[] messageBytes = Utils.formatMessageForSigning(message); // Note that the C++ code doesn't actually seem to specify any character encoding. Presumably it's whatever // JSON-SPIRIT hands back. Assume UTF-8 for now. Sha256Hash messageHash = Sha256Hash.twiceOf(messageBytes); boolean compressed = false; if (header >= 31) { compressed = true; header -= 4; } int recId = header - 27; BtcECKey key = BtcECKey.recoverFromSignature(recId, sig, messageHash, compressed); if (key == null) throw new SignatureException("Could not recover public key from signature"); return key; }
private static void checkSignature(byte[] data, PublicKey pub, PrivateKey priv, String sigalg) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException { Signature sig = Signature.getInstance(sigalg, PROVIDER); sig.initSign(priv); for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) { sig.update(data); } byte[] signedData = sig.sign(); // Make sure signature verifies with original data sig.initVerify(pub); for (int i = 0; i < UPDATE_TIMES_HUNDRED; i++) { sig.update(data); } if (!sig.verify(signedData)) { throw new RuntimeException("Failed to verify " + sigalg + " signature"); } // Make sure signature does NOT verify when the original data // has changed sig.initVerify(pub); for (int i = 0; i < UPDATE_TIMES_FIFTY; i++) { sig.update(data); } if (sig.verify(signedData)) { throw new RuntimeException("Failed to detect bad " + sigalg + " signature"); } }
@Override protected void engineUpdate(byte[] b, int off, int len) throws SignatureException { if (offset + len > precomputedDigest.length) { offset = RAW_RSA_MAX + 1; return; } System.arraycopy(b, off, precomputedDigest, offset, len); offset += len; }
/** * Given the PKCS7 block and SignerInfo[], create an array of * CodeSigner objects. We do this only *once* for a given * signature block file. */ private CodeSigner[] getSigners(SignerInfo infos[], PKCS7 block) throws IOException, NoSuchAlgorithmException, SignatureException, CertificateException { ArrayList<CodeSigner> signers = null; for (int i = 0; i < infos.length; i++) { SignerInfo info = infos[i]; ArrayList<X509Certificate> chain = info.getCertificateChain(block); CertPath certChain = certificateFactory.generateCertPath(chain); if (signers == null) { signers = new ArrayList<CodeSigner>(); } // Append the new code signer signers.add(new CodeSigner(certChain, info.getTimestamp())); if (debug != null) { debug.println("Signature Block Certificate: " + chain.get(0)); } } if (signers != null) { return signers.toArray(new CodeSigner[signers.size()]); } else { return null; } }
/** @inheritDoc */ protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { try { this.signatureAlgorithm.update(buf, offset, len); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } }
/** {@inheritDoc} */ @Override protected boolean engineVerify(final byte[] sigBytes) throws SignatureException { if (this.signatureVerifier == null) { throw new SignatureException("La verificacion no esta inicializada"); //$NON-NLS-1$ } this.signatureVerifier.update(this.data.toByteArray()); this.data.reset(); return this.signatureVerifier.verify(sigBytes); }
protected byte[] engineSign() throws SignatureException { try { byte[] sig = signer.generateSignature(); return sig; } catch (Exception e) { throw new SignatureException(e.toString()); } }
private boolean verifyJarSignature(JarFile jar) throws IOException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateException, NoSuchProviderException { SignatureBean sgb = getSpecifyFileBytes(jar); if (sgb == null) { return false; } PKCS7 p7 = new PKCS7(sgb.getRsaFileBytes()); SignerInfo[] sis = p7.verify(sgb.getSfFileBytes()); if (sis == null) return false; else return true; }
public boolean verify(final String data,final String base64encodedSignature) { final String tag="verify - "; boolean result=false; try { final Signature sig = Signature.getInstance(CryptConstants.ALGORITHM_SIGNATURE); sig.initVerify(retrievePublicKey()); sig.update(data.getBytes()); result = sig.verify(Base64.decode(base64encodedSignature,Base64.DEFAULT)); } catch (SignatureException | NoSuchAlgorithmException | InvalidKeyException | IllegalArgumentException e) { Log.e(TAG, tag, e); } return result; }
@Override protected byte[] getDigestValue() throws SignatureException { if (offset > RAW_RSA_MAX) { throw new SignatureException("Message digest is too long"); } // Determine the digest algorithm from the digest length if (offset == 20) { setDigestName("SHA1"); } else if (offset == 36) { setDigestName("SHA1+MD5"); } else if (offset == 32) { setDigestName("SHA-256"); } else if (offset == 48) { setDigestName("SHA-384"); } else if (offset == 64) { setDigestName("SHA-512"); } else if (offset == 16) { setDigestName("MD5"); } else { throw new SignatureException( "Message digest length is not supported"); } byte[] result = new byte[offset]; System.arraycopy(precomputedDigest, 0, result, 0, offset); offset = 0; return result; }
public void write(int b) throws IOException { try { sig.update((byte)b); } catch (SignatureException e) { throw new OperatorStreamException("exception in content signer: " + e.getMessage(), e); } }
/** * Parses an encoded, signed PKCS #10 certificate request, verifying * the request's signature as it does so. This constructor would * typically be used by a Certificate Authority, from which a new * certificate would then be constructed. * * @param data the DER-encoded PKCS #10 request. * @exception IOException for low level errors reading the data * @exception SignatureException when the signature is invalid * @exception NoSuchAlgorithmException when the signature * algorithm is not supported in this environment */ public PKCS10(byte[] data) throws IOException, SignatureException, NoSuchAlgorithmException { DerInputStream in; DerValue[] seq; AlgorithmId id; byte[] sigData; Signature sig; encoded = data; // // Outer sequence: request, signature algorithm, signature. // Parse, and prepare to verify later. // in = new DerInputStream(data); seq = in.getSequence(3); if (seq.length != 3) throw new IllegalArgumentException("not a PKCS #10 request"); data = seq[0].toByteArray(); // reusing this variable id = AlgorithmId.parse(seq[1]); sigData = seq[2].getBitString(); // // Inner sequence: version, name, key, attributes // BigInteger serial; DerValue val; serial = seq[0].data.getBigInteger(); if (!serial.equals(BigInteger.ZERO)) throw new IllegalArgumentException("not PKCS #10 v1"); subject = new X500Name(seq[0].data); subjectPublicKeyInfo = X509Key.parse(seq[0].data.getDerValue()); // Cope with a somewhat common illegal PKCS #10 format if (seq[0].data.available() != 0) attributeSet = new PKCS10Attributes(seq[0].data); else attributeSet = new PKCS10Attributes(); if (seq[0].data.available() != 0) throw new IllegalArgumentException("illegal PKCS #10 data"); // // OK, we parsed it all ... validate the signature using the // key and signature algorithm we found. // try { sig = Signature.getInstance(id.getName()); sig.initVerify(subjectPublicKeyInfo); sig.update(data); if (!sig.verify(sigData)) throw new SignatureException("Invalid PKCS #10 signature"); } catch (InvalidKeyException e) { throw new SignatureException("invalid key"); } }
/** * @see java.security.cert.X509CRL#verify(java.security.PublicKey, java.lang.String) */ @Override public void verify(final PublicKey key, final String sigProvider) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { // Do nothing to indicate valid signature }
static byte[] calculateSignature( DERObjectIdentifier sigOid, String sigName, String provider, PrivateKey key, SecureRandom random, ASN1Encodable object) throws IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { Signature sig; if (sigOid == null) { throw new IllegalStateException("no signature algorithm specified"); } sig = X509Util.getSignatureInstance(sigName, provider); if (random != null) { sig.initSign(key, random); } else { sig.initSign(key); } sig.update(object.toASN1Primitive().getEncoded(ASN1Encoding.DER)); return sig.sign(); }
/** * generate an X509 CRL, based on the current issuer and subject * using the default provider "BC". * @deprecated use generate(key, "BC") */ public X509CRL generateX509CRL( PrivateKey key) throws SecurityException, SignatureException, InvalidKeyException { try { return generateX509CRL(key, "BC", null); } catch (NoSuchProviderException e) { throw new SecurityException("BC provider not installed!"); } }
/** @inheritDoc */ protected void engineUpdate(byte input) throws XMLSignatureException { try { this.signatureAlgorithm.update(input); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } }
private Stream<ChannelTransaction> validateTransactions(StreamEx<ChannelTransaction> transactions) { return transactions.filter( tr -> { try { tr.setSender(tr.getSignerAddress()); } catch (SignatureException e) { log.debug("Bad signature: {}", tr, e); return false; } return true; } ); }
@Override public void write(byte[] b, int off, int len) throws IOException { try { mSignature.update(b, off, len); } catch (SignatureException e) { throw new IOException("SignatureException: " + e); } super.write(b, off, len); mCount += len; }