use of java.security.PublicKey in project OpenAM by OpenRock.
the class KeyUtil method getEncryptionInfo.
/**
* Returns the <code>EncInfo</code> from the <code>KeyDescriptor</code>.
*
* @param kd the M<code>KeyDescriptor</code> object.
* @param entityID the entity identfier
* @param role the role of the entity . Value can be PEP or PDP.
* @return <code>EncInfo</code> the encryption info.
*/
private static EncInfo getEncryptionInfo(KeyDescriptorType kd, String entityID, String role) {
String classMethod = "KeyUtil:getEncryptionInfo:";
java.security.cert.X509Certificate cert = getCert(kd);
if (cert == null) {
SAML2SDKUtils.debug.error(classMethod + "No encryption cert for entityID=" + entityID + " in " + role + " role.");
return null;
}
List emList = kd.getEncryptionMethod();
EncryptionMethodType em = null;
String algorithm = null;
int keySize = 0;
if (emList != null && !emList.isEmpty()) {
em = (EncryptionMethodType) emList.get(0);
if (em != null) {
algorithm = em.getAlgorithm();
List cList = em.getContent();
if (cList != null) {
keySize = ((EncryptionMethodType.KeySize) (cList.get(0))).getValue().intValue();
}
}
}
if (algorithm == null || algorithm.length() == 0) {
algorithm = XMLCipher.AES_128;
keySize = 128;
}
PublicKey pk = cert.getPublicKey();
EncInfo encInfo = null;
if (pk != null) {
encInfo = new EncInfo(pk, algorithm, keySize);
}
String index = entityID.trim() + "|" + role;
if (encInfo != null) {
encHash.put(index, encInfo);
}
return encInfo;
}
use of java.security.PublicKey in project OpenAM by OpenRock.
the class JwtGenerator method main.
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.out.println("Usage: JwtGenerator <subject> <issuer> <audience>");
System.exit(1);
}
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);
KeyPair keyPair = keyGen.genKeyPair();
PublicKey publicKey = keyPair.getPublic();
long validTime = System.currentTimeMillis() + 1000 * 60 * 60 * 24 / 2;
String jwt = new JwtBuilderFactory().jws(new SigningManager().newRsaSigningHandler(keyPair.getPrivate())).headers().alg(JwsAlgorithm.RS256).done().claims(new JwtClaimsSet(json(object(field("iss", args[0]), field("sub", args[1]), field("aud", args[2]), field("exp", validTime / 1000))).asMap())).build();
System.out.println("JWT: " + jwt);
Calendar expiry = Calendar.getInstance();
expiry.add(Calendar.DAY_OF_YEAR, 7);
X509CertInfo info = new X509CertInfo();
CertificateValidity interval = new CertificateValidity(new Date(), new Date(validTime));
BigInteger sn = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name("CN=ForgeRock,L=Bristol,C=GB");
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId algo = new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
// Sign the cert to identify the algorithm that's used.
X509CertImpl cert = new X509CertImpl(info);
cert.sign(keyPair.getPrivate(), "SHA256withRSA");
System.out.println("Certificate:");
BASE64Encoder encoder = new BASE64Encoder();
System.out.println(X509Factory.BEGIN_CERT);
encoder.encodeBuffer(cert.getEncoded(), System.out);
System.out.println(X509Factory.END_CERT);
}
use of java.security.PublicKey in project OpenAM by OpenRock.
the class IdTokenClaimGathererTest method mockOAuth2Uris.
private OAuth2UrisFactory<RealmInfo> mockOAuth2Uris() throws NotFoundException, ServerException {
OAuth2UrisFactory<RealmInfo> oAuth2UrisFactory = mock(OAuth2UrisFactory.class);
given(oAuth2UrisFactory.get(oAuth2Request)).willReturn(oAuth2Uris);
PublicKey publicKey = mock(PublicKey.class);
KeyPair keyPair = new KeyPair(publicKey, null);
given(oAuth2ProviderSettings.getServerKeyPair()).willReturn(keyPair);
return oAuth2UrisFactory;
}
use of java.security.PublicKey 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.PublicKey in project OpenAM by OpenRock.
the class OpenAMOAuth2ProviderSettings method getJWKSet.
public JsonValue getJWKSet() throws ServerException {
synchronized (jwks) {
if (jwks.isEmpty()) {
PublicKey key = getServerKeyPair().getPublic();
jwks.add(createRSAJWK((RSAPublicKey) key, KeyUse.SIG, JwsAlgorithm.RS256.name()));
}
}
return new JsonValue(Collections.singletonMap("keys", jwks));
}
Aggregations