下面列出了怎么用java.security.SignatureException的API类实例代码及写法,或者点击链接到github查看源代码。
private static boolean test(Certificate target, Certificate signer,
String title, boolean expected) throws Exception {
System.out.print("Checking " + title + ": expected: " +
(expected ? " verified" : "NOT verified"));
boolean actual;
try {
PublicKey pubKey = signer.getPublicKey();
target.verify(pubKey);
actual = true;
} catch (SignatureException se) {
actual = false;
}
System.out.println(", actual: " +
(actual ? " verified" : "NOT verified"));
return actual == expected;
}
@Test
public void testCryptoExceptions() {
CryptoException ex = new CryptoException();
assertNotNull(ex);
assertEquals(ex.getCode(), CryptoException.CRYPTO_ERROR);
assertNotNull(new CryptoException(new NoSuchAlgorithmException()));
assertNotNull(new CryptoException(new InvalidKeyException()));
assertNotNull(new CryptoException(new NoSuchProviderException()));
assertNotNull(new CryptoException(new SignatureException()));
assertNotNull(new CryptoException(new FileNotFoundException()));
assertNotNull(new CryptoException(new IOException()));
assertNotNull(new CryptoException(new CertificateException()));
assertNotNull(new CryptoException(new InvalidKeySpecException()));
assertNotNull(new CryptoException(new OperatorCreationException("unit-test")));
assertNotNull(new CryptoException(new PKCSException("unit-test")));
assertNotNull(new CryptoException(new CMSException("unit-test")));
ex = new CryptoException(CryptoException.CERT_HASH_MISMATCH, "X.509 Certificate hash mismatch");
assertEquals(ex.getCode(), CryptoException.CERT_HASH_MISMATCH);
}
private boolean saveNewRootCACertificate() {
if (caKeyPair == null) {
throw new CloudRuntimeException("Cannot issue self-signed root CA certificate as CA keypair is not initialized");
}
try {
LOG.debug("Generating root CA certificate");
final X509Certificate rootCaCertificate = CertUtils.generateV3Certificate(
null, caKeyPair, caKeyPair.getPublic(),
rootCAIssuerDN.value(), CAManager.CertSignatureAlgorithm.value(),
getCaValidityDays(), null, null);
if (!configDao.update(rootCACertificate.key(), rootCACertificate.category(), CertUtils.x509CertificateToPem(rootCaCertificate))) {
LOG.error("Failed to update RootCA public/x509 certificate");
}
} catch (final CertificateException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException | InvalidKeyException | OperatorCreationException | IOException e) {
LOG.error("Failed to generate RootCA certificate from private/public keys due to exception:", e);
return false;
}
return loadRootCACertificate();
}
protected long doBatch(long numIterations) throws InterruptedException {
try {
for (long i = 0; i < numIterations; i++) {
if (exeMode == 1) {
sig.update(data);
signatureBytes = sig.sign();
} else if (exeMode == 2) {
sig.update(data);
sig.verify(signatureBytes, 0, signatureBytes.length);
}
}
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return numIterations;
}
private Certificate validateServerKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableEntryException,
InvalidKeyException, NoSuchProviderException, SignatureException {
serverConfig = objectMapper.readValue(new ByteArrayInputStream(serverConfigFileOutputStream.toByteArray()), TlsConfig.class);
KeyStore serverKeyStore = KeyStoreUtils.getKeyStore(serverConfig.getKeyStoreType());
serverKeyStore.load(new ByteArrayInputStream(serverKeyStoreOutputStream.toByteArray()), serverConfig.getKeyStorePassword().toCharArray());
String keyPassword = serverConfig.getKeyPassword();
KeyStore.Entry serverKeyEntry = serverKeyStore.getEntry(TlsToolkitStandalone.NIFI_KEY,
new KeyStore.PasswordProtection(keyPassword == null ? serverConfig.getKeyStorePassword().toCharArray() : keyPassword.toCharArray()));
assertTrue(serverKeyEntry instanceof KeyStore.PrivateKeyEntry);
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) serverKeyEntry;
Certificate[] certificateChain = privateKeyEntry.getCertificateChain();
assertEquals(1, certificateChain.length);
Certificate caCertificate = certificateChain[0];
caCertificate.verify(caCertificate.getPublicKey());
assertPrivateAndPublicKeyMatch(privateKeyEntry.getPrivateKey(), caCertificate.getPublicKey());
return caCertificate;
}
@Override
protected synchronized int engineSign(byte[] outbuf, int offset, int len)
throws SignatureException {
boolean doCancel = true;
try {
if (outbuf == null || (offset < 0) || (outbuf.length < (offset + sigLength))
|| (len < sigLength)) {
throw new SignatureException("Invalid output buffer. offset: " +
offset + ". len: " + len + ". sigLength: " + sigLength);
}
int rv = doFinal(outbuf, offset, sigLength);
doCancel = false;
if (rv < 0) {
throw new SignatureException(new UcryptoException(-rv));
}
return sigLength;
} finally {
reset(doCancel);
}
}
public TestData(PublicKey pubArg, PrivateKey privArg)
throws NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchProviderException, InvalidKeyException, SignatureException,
UnsupportedEncodingException, InvalidAlgorithmParameterException {
pub = pubArg;
priv = privArg;
int signedDataId = TagsEnum.TAG_UAFV1_SIGNED_DATA.id;
int signedDataLength = 200;
dataForSigning[0] = (byte) (signedDataId & 0x00ff);
dataForSigning[1] = (byte) (signedDataId & 0xff00);
dataForSigning[2] = (byte) (signedDataLength & 0x00ff);
dataForSigning[3] = (byte) (signedDataLength & 0xff00);
//signature = NamedCurve.sign(priv, dataForSigning);
rsSignature = NamedCurve.signAndFromatToRS(priv,
SHA.sha(dataForSigning, "SHA-1"));
}
/**
* Creates digital signature over the data stream using the s private key.
*
* @param data - Data to sign.
* @throws CertificateException - on Error.
*/
@Override
public byte[] signData(byte[] data) throws CertificateException {
try {
Signature sign = Signature.getInstance(securityConfig.getSignatureAlgo(),
securityConfig.getProvider());
sign.initSign(getPrivateKey());
sign.update(data);
return sign.sign();
} catch (NoSuchAlgorithmException | NoSuchProviderException
| InvalidKeyException | SignatureException e) {
getLogger().error("Error while signing the stream", e);
throw new CertificateException("Error while signing the stream", e,
CRYPTO_SIGN_ERROR);
}
}
@Test
public void testRSAAuthenticationToken()
throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {
String tokenstr =
"[email protected][email protected]@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwg[email protected]WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=";
RSAAuthenticationToken token = RSAAuthenticationToken.fromStr(tokenstr);
String contents = token.plainToken();
Assert.assertEquals(
"[email protected][email protected]@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ",
contents);
String sign = token.getSign();
Assert.assertEquals(
"WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=",
sign);
String pubKey =
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxKl5TNUTec7fL2degQcCk6vKf3c0wsfNK5V6elKzjWxm0MwbRj/UeR20VSnicBmVIOWrBS9LiERPPvjmmWUOSS2vxwr5XfhBhZ07gCAUNxBOTzgMo5nE45DhhZu5Jzt5qSV6o10Kq7+fCCBlDZ1UoWxZceHkUt5AxcrhEDulFjQIDAQAB";
Assert.assertTrue(RSAUtils.verify(pubKey, sign, contents));
}
private static boolean test(Certificate target, Certificate signer,
String title, boolean expected) throws Exception {
System.out.print("Checking " + title + ": expected: " +
(expected ? " verified" : "NOT verified"));
boolean actual;
try {
PublicKey pubKey = signer.getPublicKey();
target.verify(pubKey);
actual = true;
} catch (SignatureException se) {
actual = false;
}
System.out.println(", actual: " +
(actual ? " verified" : "NOT verified"));
return actual == expected;
}
@Test(expectedExceptions = SignatureException.class)
public void fullEncryptionBadSignature() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("hashKey").setN("666");
encryptor.decryptAllFieldsExcept(Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version");
}
@Override
public void write(int arg0) {
super.write(arg0);
try {
sig.update((byte)arg0);
} catch (SignatureException e) {
throw new RuntimeException(e);
}
}
private static byte[] sign(byte [] bytes, PrivateKey pk){
Signature dsa;
try {
dsa = Signature.getInstance("SHA1withDSA", "SUN");
dsa.initSign(pk);
dsa.update(bytes);
return dsa.sign();
} catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException e) {
throw new RuntimeException(e);
}
}
/**
* 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<>();
}
// Append the new code signer. If timestamp is invalid, this
// jar will be treated as unsigned.
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;
}
}
/**
* Catch (self-signed) SSL errors and test if they correspond to Syncthing's certificate.
*/
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
try {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// The mX509Certificate field is not available for ICS- devices
Log.w(TAG, "Skipping certificate check for devices <ICS");
handler.proceed();
return;
}
// Use reflection to access the private mX509Certificate field of SslCertificate
SslCertificate sslCert = error.getCertificate();
Field f = sslCert.getClass().getDeclaredField("mX509Certificate");
f.setAccessible(true);
X509Certificate cert = (X509Certificate)f.get(sslCert);
if (cert == null) {
Log.w(TAG, "X509Certificate reference invalid");
handler.cancel();
return;
}
cert.verify(mCaCert.getPublicKey());
handler.proceed();
} catch (NoSuchFieldException|IllegalAccessException|CertificateException|
NoSuchAlgorithmException|InvalidKeyException|NoSuchProviderException|
SignatureException e) {
Log.w(TAG, e);
handler.cancel();
}
}
public final void verify(
PublicKey key,
String sigProvider)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException, SignatureException
{
String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm());
Signature signature = Signature.getInstance(sigName, sigProvider);
checkSignature(key, signature);
}
/**
* 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<>();
}
// Append the new code signer. If timestamp is invalid, this
// jar will be treated as unsigned.
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);
}
}
@Override
protected void engineUpdate(byte b) throws SignatureException {
if (offset >= precomputedDigest.length) {
offset = RAW_RSA_MAX + 1;
return;
}
precomputedDigest[offset++] = b;
}
protected void engineUpdate(
byte[] b,
int off,
int len)
throws SignatureException
{
digest.update(b, off, len);
}
/**
* 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!");
}
}
@Test(expectedExceptions = SignatureException.class)
public void signedOnlyNoSignature() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.remove(encryptor.getSignatureFieldName());
encryptor.decryptAllFieldsExcept(encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
/**
* generate an X509 certificate, based on the current issuer and subject,
* using the passed in provider for the signing.
*/
public X509Certificate generate(
PrivateKey key,
String provider)
throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
{
return generate(key, provider, null);
}
boolean verifySignature(byte[] sigData, int sigOffset, int sigLength,
int updateOffset, int updateLength)
throws InvalidKeyException, SignatureException {
signature.initVerify(pubkey);
signature.update(cleartext, updateOffset, updateLength);
return signature.verify(sigData, sigOffset, sigLength);
}
private static boolean verifyMessageSignature(PublicKey publicKey,
String messageString, byte[] signature)
throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
Signature sign = Signature.getInstance("SHA256withRSA/PSS", new BouncyCastleProvider());
byte[] message = messageString.getBytes();
sign.initVerify(publicKey);
sign.update(message);
return sign.verify(signature);
}
/**
* generate an X509 certificate, based on the current issuer and subject,
* using the passed in provider for the signing.
* @deprecated use generate()
*/
public X509Certificate generateX509Certificate(
PrivateKey key,
String provider)
throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException
{
return generateX509Certificate(key, provider, null);
}
@Test
public void handleRequestTest() throws SignatureException, IOException {
ContainerRequestContext requestContext = createMock(ContainerRequestContext.class);
ClassResourceInfo resourceClass = createMock(ClassResourceInfo.class);
HttpHeaders headers = createMock(HttpHeaders.class);
UriInfo uriInfo = createMock(UriInfo.class);
String date = DateFormatUtils.SMTP_DATETIME_FORMAT.format(new Date());
String resource = "/questionnaires/61";
String method = "GET";
String stringToSign = new StringBuilder().append(method).append(" ").append(resource).append("\n").append(date)
.toString();
String apiKey = "B868UOHUTKUDWXM";
String secret = "IQO27YUZO8NJ7RADIK6SJ9BQZNYP4EMO";
String signature = HMACSignature.calculateRFC2104HMAC(stringToSign, secret);
String authToken = generateAuth(apiKey, signature);
expect(requestContext.getMethod()).andReturn(method);
expect(uriInfo.getRequestUri()).andReturn(URI.create("http://localhost:8080/gazpachoquest-rest-web/api/" + resource));
expect(requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).andReturn(authToken);
expect(requestContext.getHeaderString(HttpHeaders.DATE)).andReturn(date);
expect(headers.getRequestHeader(HttpHeaders.AUTHORIZATION)).andReturn(Arrays.asList(authToken));
expect(headers.getRequestHeader(HttpHeaders.DATE)).andReturn(Arrays.asList(date));
expect(uriInfo.getPath()).andReturn(resource.substring(1));
replay(requestContext,resourceClass, uriInfo, headers);
loginShiroFilter.setUriInfo(uriInfo);
loginShiroFilter.setHeaders(headers);
loginShiroFilter.filter(requestContext);
}
/** @inheritDoc */
protected void engineUpdate(byte[] input) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/**
* generate an X509 certificate, based on the current issuer and subject
* using the passed in provider for the signing.
*/
public X509CRL generate(
PrivateKey key,
String provider)
throws CRLException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
{
return generate(key, provider, 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);
}
}