use of java.security.SignatureException in project wycheproof by google.
the class RsaSignatureTest method testVectors.
/**
* Tests an RSA signature implementation with a number of vectors. The test assumes that the first
* test vector is valid, but everything else is invalid. Many of the test vectors are derived by
* signing modified ASN encodings. Hence accepting an invalid signature does not mean by itself
* that the implementation can be broken, but often points to a bigger problem. The test expects
* that verifying an invalid signature either leads to a return value False or will result in a
* SignatureException. Verifying an RSA signature should not result in an RuntimeException, so
* that reasonably implementated applications can be expected to catch and treat invalid
* signatures appropriately. While RuntimeExceptions may not be exploitable, they often indicate
* an oversight in the implementation of the provider.
* https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
*/
public void testVectors(RSAPublicKeySpec key, String algorithm, String[] testvectors) throws Exception {
byte[] message = "Test".getBytes("UTF-8");
Signature verifier = Signature.getInstance(algorithm);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pub = kf.generatePublic(key);
int errors = 0;
boolean first = true;
for (String signature : testvectors) {
byte[] signatureBytes = TestUtil.hexToBytes(signature);
verifier.initVerify(pub);
verifier.update(message);
boolean verified = false;
try {
verified = verifier.verify(signatureBytes);
} catch (SignatureException ex) {
// verify can throw SignatureExceptions if the signature is malformed.
}
if (first && !verified) {
System.out.println("Valid signature not verified:" + signature);
errors++;
} else if (!first && verified) {
System.out.println("Incorrect signature verified:" + signature);
errors++;
}
first = false;
}
assertEquals(0, errors);
}
use of java.security.SignatureException in project XobotOS by xamarin.
the class RecoverySystem method verifyPackage.
/**
* Verify the cryptographic signature of a system update package
* before installing it. Note that the package is also verified
* separately by the installer once the device is rebooted into
* the recovery system. This function will return only if the
* package was successfully verified; otherwise it will throw an
* exception.
*
* Verification of a package can take significant time, so this
* function should not be called from a UI thread. Interrupting
* the thread while this function is in progress will result in a
* SecurityException being thrown (and the thread's interrupt flag
* will be cleared).
*
* @param packageFile the package to be verified
* @param listener an object to receive periodic progress
* updates as verification proceeds. May be null.
* @param deviceCertsZipFile the zip file of certificates whose
* public keys we will accept. Verification succeeds if the
* package is signed by the private key corresponding to any
* public key in this file. May be null to use the system default
* file (currently "/system/etc/security/otacerts.zip").
*
* @throws IOException if there were any errors reading the
* package or certs files.
* @throws GeneralSecurityException if verification failed
*/
public static void verifyPackage(File packageFile, ProgressListener listener, File deviceCertsZipFile) throws IOException, GeneralSecurityException {
long fileLen = packageFile.length();
RandomAccessFile raf = new RandomAccessFile(packageFile, "r");
try {
int lastPercent = 0;
long lastPublishTime = System.currentTimeMillis();
if (listener != null) {
listener.onProgress(lastPercent);
}
raf.seek(fileLen - 6);
byte[] footer = new byte[6];
raf.readFully(footer);
if (footer[2] != (byte) 0xff || footer[3] != (byte) 0xff) {
throw new SignatureException("no signature in file (no footer)");
}
int commentSize = (footer[4] & 0xff) | ((footer[5] & 0xff) << 8);
int signatureStart = (footer[0] & 0xff) | ((footer[1] & 0xff) << 8);
Log.v(TAG, String.format("comment size %d; signature start %d", commentSize, signatureStart));
byte[] eocd = new byte[commentSize + 22];
raf.seek(fileLen - (commentSize + 22));
raf.readFully(eocd);
// end-of-central-directory record.
if (eocd[0] != (byte) 0x50 || eocd[1] != (byte) 0x4b || eocd[2] != (byte) 0x05 || eocd[3] != (byte) 0x06) {
throw new SignatureException("no signature in file (bad footer)");
}
for (int i = 4; i < eocd.length - 3; ++i) {
if (eocd[i] == (byte) 0x50 && eocd[i + 1] == (byte) 0x4b && eocd[i + 2] == (byte) 0x05 && eocd[i + 3] == (byte) 0x06) {
throw new SignatureException("EOCD marker found after start of EOCD");
}
}
// The following code is largely copied from
// JarUtils.verifySignature(). We could just *call* that
// method here if that function didn't read the entire
// input (ie, the whole OTA package) into memory just to
// compute its message digest.
BerInputStream bis = new BerInputStream(new ByteArrayInputStream(eocd, commentSize + 22 - signatureStart, signatureStart));
ContentInfo info = (ContentInfo) ContentInfo.ASN1.decode(bis);
SignedData signedData = info.getSignedData();
if (signedData == null) {
throw new IOException("signedData is null");
}
Collection encCerts = signedData.getCertificates();
if (encCerts.isEmpty()) {
throw new IOException("encCerts is empty");
}
// Take the first certificate from the signature (packages
// should contain only one).
Iterator it = encCerts.iterator();
X509Certificate cert = null;
if (it.hasNext()) {
cert = new X509CertImpl((org.apache.harmony.security.x509.Certificate) it.next());
} else {
throw new SignatureException("signature contains no certificates");
}
List sigInfos = signedData.getSignerInfos();
SignerInfo sigInfo;
if (!sigInfos.isEmpty()) {
sigInfo = (SignerInfo) sigInfos.get(0);
} else {
throw new IOException("no signer infos!");
}
// Check that the public key of the certificate contained
// in the package equals one of our trusted public keys.
HashSet<Certificate> trusted = getTrustedCerts(deviceCertsZipFile == null ? DEFAULT_KEYSTORE : deviceCertsZipFile);
PublicKey signatureKey = cert.getPublicKey();
boolean verified = false;
for (Certificate c : trusted) {
if (c.getPublicKey().equals(signatureKey)) {
verified = true;
break;
}
}
if (!verified) {
throw new SignatureException("signature doesn't match any trusted key");
}
// The signature cert matches a trusted key. Now verify that
// the digest in the cert matches the actual file data.
// The verifier in recovery *only* handles SHA1withRSA
// signatures. SignApk.java always uses SHA1withRSA, no
// matter what the cert says to use. Ignore
// cert.getSigAlgName(), and instead use whatever
// algorithm is used by the signature (which should be
// SHA1withRSA).
String da = sigInfo.getDigestAlgorithm();
String dea = sigInfo.getDigestEncryptionAlgorithm();
String alg = null;
if (da == null || dea == null) {
// fall back to the cert algorithm if the sig one
// doesn't look right.
alg = cert.getSigAlgName();
} else {
alg = da + "with" + dea;
}
Signature sig = Signature.getInstance(alg);
sig.initVerify(cert);
// The signature covers all of the OTA package except the
// archive comment and its 2-byte length.
long toRead = fileLen - commentSize - 2;
long soFar = 0;
raf.seek(0);
byte[] buffer = new byte[4096];
boolean interrupted = false;
while (soFar < toRead) {
interrupted = Thread.interrupted();
if (interrupted)
break;
int size = buffer.length;
if (soFar + size > toRead) {
size = (int) (toRead - soFar);
}
int read = raf.read(buffer, 0, size);
sig.update(buffer, 0, read);
soFar += read;
if (listener != null) {
long now = System.currentTimeMillis();
int p = (int) (soFar * 100 / toRead);
if (p > lastPercent && now - lastPublishTime > PUBLISH_PROGRESS_INTERVAL_MS) {
lastPercent = p;
lastPublishTime = now;
listener.onProgress(lastPercent);
}
}
}
if (listener != null) {
listener.onProgress(100);
}
if (interrupted) {
throw new SignatureException("verification was interrupted");
}
if (!sig.verify(sigInfo.getEncryptedDigest())) {
throw new SignatureException("signature digest verification failed");
}
} finally {
raf.close();
}
}
use of java.security.SignatureException in project XobotOS by xamarin.
the class SHA1withDSA_SignatureImpl method checkSignature.
private boolean checkSignature(byte[] sigBytes, int offset, int length) throws SignatureException {
// names of below BigIntegers are the same as they are defined in DSA standard
BigInteger r, s, w;
BigInteger u1, u2, v;
// parameters and public key
BigInteger p, q, g, y;
DSAParams params;
int n1, n2;
byte[] bytes;
byte[] digest;
// checking up on signature's ASN1
try {
byte dummy;
n1 = sigBytes[offset + 3];
n2 = sigBytes[offset + n1 + 5];
if (sigBytes[offset + 0] != 0x30 || sigBytes[offset + 2] != 2 || sigBytes[offset + n1 + 4] != 2 || sigBytes[offset + 1] != (n1 + n2 + 4) || n1 > 21 || n2 > 21 || (length != 0 && (sigBytes[offset + 1] + 2) > length)) {
throw new SignatureException("signature bytes have invalid encoding");
}
// to check length of sigBytes
dummy = sigBytes[5 + n1 + n2];
} catch (ArrayIndexOutOfBoundsException e) {
throw new SignatureException("bad argument: byte[] is too small");
}
digest = msgDigest.digest();
bytes = new byte[n1];
System.arraycopy(sigBytes, offset + 4, bytes, 0, n1);
r = new BigInteger(bytes);
bytes = new byte[n2];
System.arraycopy(sigBytes, offset + 6 + n1, bytes, 0, n2);
s = new BigInteger(bytes);
params = dsaKey.getParams();
p = params.getP();
q = params.getQ();
g = params.getG();
y = ((DSAPublicKey) dsaKey).getY();
if (r.signum() != 1 || r.compareTo(q) != -1 || s.signum() != 1 || s.compareTo(q) != -1) {
return false;
}
w = s.modInverse(q);
u1 = (new BigInteger(1, digest)).multiply(w).mod(q);
u2 = r.multiply(w).mod(q);
v = g.modPow(u1, p).multiply(y.modPow(u2, p)).mod(p).mod(q);
if (v.compareTo(r) != 0) {
return false;
}
return true;
}
use of java.security.SignatureException in project XobotOS by xamarin.
the class X509CRLImpl method verify.
/**
* @see java.security.cert.X509CRL#verify(PublicKey key, String sigProvider)
* method documentation for more info
*/
public void verify(PublicKey key, String sigProvider) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
Signature signature = Signature.getInstance(getSigAlgName(), sigProvider);
signature.initVerify(key);
byte[] tbsEncoding = tbsCertList.getEncoded();
signature.update(tbsEncoding, 0, tbsEncoding.length);
if (!signature.verify(crl.getSignatureValue())) {
throw new SignatureException("Signature was not verified");
}
}
use of java.security.SignatureException in project XobotOS by xamarin.
the class X509CertImpl method verify.
@Override
public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
Signature signature;
try {
if (sigProvider == null) {
signature = OpenSSLSignature.getInstance(getSigAlgName());
} else {
signature = Signature.getInstance(getSigAlgName(), sigProvider);
}
} catch (NoSuchAlgorithmException ignored) {
signature = Signature.getInstance(getSigAlgName(), sigProvider);
}
signature.initVerify(key);
// retrieve the encoding of the TBSCertificate structure
byte[] tbsCertificateLocal = getTbsCertificateInternal();
// compute and verify the signature
signature.update(tbsCertificateLocal, 0, tbsCertificateLocal.length);
if (!signature.verify(certificate.getSignatureValue())) {
throw new SignatureException("Signature was not verified");
}
}
Aggregations