use of sun.misc.BASE64Encoder 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 sun.misc.BASE64Encoder in project otertool by wuntee.
the class JarSigner method signJar.
void signJar(String jarName, String alias, String[] args) throws Exception {
boolean aliasUsed = false;
X509Certificate tsaCert = null;
if (sigfile == null) {
sigfile = alias;
aliasUsed = true;
}
if (sigfile.length() > 8) {
sigfile = sigfile.substring(0, 8).toUpperCase();
} else {
sigfile = sigfile.toUpperCase();
}
StringBuilder tmpSigFile = new StringBuilder(sigfile.length());
for (int j = 0; j < sigfile.length(); j++) {
char c = sigfile.charAt(j);
if (!((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '-') || (c == '_'))) {
if (aliasUsed) {
// convert illegal characters from the alias to be _'s
c = '_';
} else {
throw new RuntimeException(rb.getString("signature filename must consist of the following characters: A-Z, 0-9, _ or -"));
}
}
tmpSigFile.append(c);
}
sigfile = tmpSigFile.toString();
String tmpJarName;
if (signedjar == null)
tmpJarName = jarName + ".sig";
else
tmpJarName = signedjar;
File jarFile = new File(jarName);
File signedJarFile = new File(tmpJarName);
// Open the jar (zip) file
try {
zipFile = new ZipFile(jarName);
} catch (IOException ioe) {
error(rb.getString("unable to open jar file: ") + jarName, ioe);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(signedJarFile);
} catch (IOException ioe) {
error(rb.getString("unable to create: ") + tmpJarName, ioe);
}
PrintStream ps = new PrintStream(fos);
ZipOutputStream zos = new ZipOutputStream(ps);
/* First guess at what they might be - we don't xclude RSA ones. */
String sfFilename = (META_INF + sigfile + ".SF").toUpperCase();
String bkFilename = (META_INF + sigfile + ".DSA").toUpperCase();
Manifest manifest = new Manifest();
Map<String, Attributes> mfEntries = manifest.getEntries();
// The Attributes of manifest before updating
Attributes oldAttr = null;
boolean mfModified = false;
boolean mfCreated = false;
byte[] mfRawBytes = null;
try {
MessageDigest[] digests = { MessageDigest.getInstance(digestalg) };
// Check if manifest exists
ZipEntry mfFile;
if ((mfFile = getManifestFile(zipFile)) != null) {
// Manifest exists. Read its raw bytes.
mfRawBytes = getBytes(zipFile, mfFile);
manifest.read(new ByteArrayInputStream(mfRawBytes));
oldAttr = (Attributes) (manifest.getMainAttributes().clone());
} else {
// Create new manifest
Attributes mattr = manifest.getMainAttributes();
mattr.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
String javaVendor = System.getProperty("java.vendor");
String jdkVersion = System.getProperty("java.version");
mattr.putValue("Created-By", jdkVersion + " (" + javaVendor + ")");
mfFile = new ZipEntry(JarFile.MANIFEST_NAME);
mfCreated = true;
}
/*
* For each entry in jar
* (except for signature-related META-INF entries),
* do the following:
*
* - if entry is not contained in manifest, add it to manifest;
* - if entry is contained in manifest, calculate its hash and
* compare it with the one in the manifest; if they are
* different, replace the hash in the manifest with the newly
* generated one. (This may invalidate existing signatures!)
*/
BASE64Encoder encoder = new JarBASE64Encoder();
Vector<ZipEntry> mfFiles = new Vector<ZipEntry>();
for (Enumeration<? extends ZipEntry> enum_ = zipFile.entries(); enum_.hasMoreElements(); ) {
ZipEntry ze = enum_.nextElement();
if (ze.getName().startsWith(META_INF)) {
// Store META-INF files in vector, so they can be written
// out first
mfFiles.addElement(ze);
if (signatureRelated(ze.getName())) {
// ignore signature-related and manifest files
continue;
}
}
if (manifest.getAttributes(ze.getName()) != null) {
// possibly update its digest attributes
if (updateDigests(ze, zipFile, digests, encoder, manifest) == true) {
mfModified = true;
}
} else if (!ze.isDirectory()) {
// Add entry to manifest
Attributes attrs = getDigestAttributes(ze, zipFile, digests, encoder);
mfEntries.put(ze.getName(), attrs);
mfModified = true;
}
}
// Recalculate the manifest raw bytes if necessary
if (mfModified) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
byte[] newBytes = baos.toByteArray();
if (mfRawBytes != null && oldAttr.equals(manifest.getMainAttributes())) {
/*
* Note:
*
* The Attributes object is based on HashMap and can handle
* continuation columns. Therefore, even if the contents are
* not changed (in a Map view), the bytes that it write()
* may be different from the original bytes that it read()
* from. Since the signature on the main attributes is based
* on raw bytes, we must retain the exact bytes.
*/
int newPos = findHeaderEnd(newBytes);
int oldPos = findHeaderEnd(mfRawBytes);
if (newPos == oldPos) {
System.arraycopy(mfRawBytes, 0, newBytes, 0, oldPos);
} else {
// cat oldHead newTail > newBytes
byte[] lastBytes = new byte[oldPos + newBytes.length - newPos];
System.arraycopy(mfRawBytes, 0, lastBytes, 0, oldPos);
System.arraycopy(newBytes, newPos, lastBytes, oldPos, newBytes.length - newPos);
newBytes = lastBytes;
}
}
mfRawBytes = newBytes;
}
// Write out the manifest
if (mfModified) {
// manifest file has new length
mfFile = new ZipEntry(JarFile.MANIFEST_NAME);
}
zos.putNextEntry(mfFile);
zos.write(mfRawBytes);
// Calculate SignatureFile (".SF") and SignatureBlockFile
ManifestDigester manDig = new ManifestDigester(mfRawBytes);
SignatureFile sf = new SignatureFile(digests, manifest, manDig, sigfile, signManifest);
if (tsaAlias != null) {
tsaCert = getTsaCert(tsaAlias);
}
SignatureFile.Block block = null;
try {
block = sf.generateBlock(privateKey, sigalg, certChain, externalSF, tsaUrl, tsaCert, signingMechanism, args, zipFile);
} catch (SocketTimeoutException e) {
// Provide a helpful message when TSA is beyond a firewall
error(rb.getString("unable to sign jar: ") + rb.getString("no response from the Timestamping Authority. ") + rb.getString("When connecting from behind a firewall then an HTTP proxy may need to be specified. ") + rb.getString("Supply the following options to jarsigner: ") + "\n -J-Dhttp.proxyHost=<hostname> " + "\n -J-Dhttp.proxyPort=<portnumber> ", e);
}
sfFilename = sf.getMetaName();
bkFilename = block.getMetaName();
ZipEntry sfFile = new ZipEntry(sfFilename);
ZipEntry bkFile = new ZipEntry(bkFilename);
long time = System.currentTimeMillis();
sfFile.setTime(time);
bkFile.setTime(time);
// signature file
zos.putNextEntry(sfFile);
sf.write(zos);
// signature block file
zos.putNextEntry(bkFile);
block.write(zos);
// vector
for (int i = 0; i < mfFiles.size(); i++) {
ZipEntry ze = mfFiles.elementAt(i);
if (!ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME) && !ze.getName().equalsIgnoreCase(sfFilename) && !ze.getName().equalsIgnoreCase(bkFilename)) {
writeEntry(zipFile, zos, ze);
}
}
// Write out all other files
for (Enumeration<? extends ZipEntry> enum_ = zipFile.entries(); enum_.hasMoreElements(); ) {
ZipEntry ze = enum_.nextElement();
if (!ze.getName().startsWith(META_INF)) {
writeEntry(zipFile, zos, ze);
}
}
} catch (IOException ioe) {
error(rb.getString("unable to sign jar: ") + ioe, ioe);
} finally {
// close the resouces
if (zipFile != null) {
zipFile.close();
zipFile = null;
}
if (zos != null) {
zos.close();
}
}
// try {
if (signedjar == null) {
// one, then delete the original.
if (!signedJarFile.renameTo(jarFile)) {
File origJar = new File(jarName + ".orig");
if (jarFile.renameTo(origJar)) {
if (signedJarFile.renameTo(jarFile)) {
origJar.delete();
} else {
MessageFormat form = new MessageFormat(rb.getString("attempt to rename signedJarFile to jarFile failed"));
Object[] source = { signedJarFile, jarFile };
error(form.format(source));
}
} else {
MessageFormat form = new MessageFormat(rb.getString("attempt to rename jarFile to origJar failed"));
Object[] source = { jarFile, origJar };
error(form.format(source));
}
}
}
if (hasExpiredCert || hasExpiringCert || notYetValidCert || badKeyUsage || badExtendedKeyUsage || badNetscapeCertType) {
logger.warn(rb.getString("Warning: "));
if (badKeyUsage) {
logger.warn(rb.getString("The signer certificate's KeyUsage extension doesn't allow code signing."));
}
if (badExtendedKeyUsage) {
logger.warn(rb.getString("The signer certificate's ExtendedKeyUsage extension doesn't allow code signing."));
}
if (badNetscapeCertType) {
logger.warn(rb.getString("The signer certificate's NetscapeCertType extension doesn't allow code signing."));
}
if (hasExpiredCert) {
logger.warn(rb.getString("The signer certificate has expired."));
} else if (hasExpiringCert) {
logger.warn(rb.getString("The signer certificate will expire within six months."));
} else if (notYetValidCert) {
logger.warn(rb.getString("The signer certificate is not yet valid."));
}
}
// no IOException thrown in the above try clause, so disable
// the catch clause.
// } catch(IOException ioe) {
// error(rb.getString("unable to sign jar: ")+ioe, ioe);
// }
}
use of sun.misc.BASE64Encoder in project adempiere by adempiere.
the class BrowserToken method getHomeToken.
private static String getHomeToken() throws UnsupportedEncodingException {
String home = Adempiere.getAdempiereHome();
BASE64Encoder encoder = new BASE64Encoder();
home = encoder.encode(home.getBytes("UTF-8"));
home = URLEncoder.encode(home, "UTF-8");
return home;
}
use of sun.misc.BASE64Encoder in project sakuli by ConSol.
the class ScreenshotDivConverter method extractScreenshotAsBase64.
protected String extractScreenshotAsBase64(Throwable exception) {
if (exception instanceof SakuliExceptionWithScreenshot) {
Path screenshotPath = ((SakuliExceptionWithScreenshot) exception).getScreenshot();
if (screenshotPath != null) {
try {
byte[] binaryScreenshot = Files.readAllBytes(screenshotPath);
String base64String = new BASE64Encoder().encode(binaryScreenshot);
for (String newLine : Arrays.asList("\n", "\r")) {
base64String = StringUtils.remove(base64String, newLine);
}
return base64String;
} catch (IOException e) {
exceptionHandler.handleException(new SakuliForwarderException(e, String.format("error during the BASE64 encoding of the screenshot '%s'", screenshotPath.toString())));
}
}
}
return null;
}
use of sun.misc.BASE64Encoder in project portal by ixinportal.
the class SignTool method verifyP7.
/**
* 验证签名(无CRL)
*
* @param signature
* 签名签名结果
* @param data
* 被签名数据
* @param dn
* 签名证书dn, 如果为空则不做匹配验证
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws SignatureException
* @throws InvalidKeyException
* @throws CertificateException
* @throws NoSuchProviderException
*/
public void verifyP7(String signature, byte[] data, String dn) throws IOException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateException, NoSuchProviderException {
if (mode != VERIFIER)
throw new IllegalStateException("call a PKCS7Tool instance not for verify.");
byte[] sign = new BASE64Decoder().decodeBuffer(signature);
PKCS7 p7 = new PKCS7(sign);
X509Certificate[] certs = p7.getCertificates();
if (debug)
for (int i = 0; i < certs.length; i++) {
X509Certificate cert = certs[i];
System.out.println("SIGNER " + i + "=\n" + cert);
System.out.println("SIGNER " + i + "=\n" + new BASE64Encoder().encode(cert.getEncoded()));
}
// 验证签名本身、证书用法、证书扩展
SignerInfo[] sis = p7.verify(data);
// check the results of the verification
if (sis == null)
throw new SignatureException("Signature failed verification, data has been tampered");
for (int i = 0; i < sis.length; i++) {
SignerInfo si = sis[i];
X509Certificate cert = si.getCertificate(p7);
// 证书是否过期验证,如果不用系统日期可用cert.checkValidity(date);
cert.checkValidity();
if (!cert.equals(rootCertificate)) {
// 验证证书签名
cert.verify(rootCertificate.getPublicKey());
}
// 验证dn
if (i == 0 && dn != null) {
X500Principal name = cert.getSubjectX500Principal();
if (!dn.equals(name.getName(X500Principal.RFC1779)) && !new X500Principal(dn).equals(name))
throw new SignatureException("Signer dn '" + name.getName(X500Principal.RFC1779) + "' does not matchs '" + dn + "'");
}
}
}
Aggregations