use of org.bouncycastle.asn1.ocsp.Signature in project Openfire by igniterealtime.
the class CertificateManager method createX509V3Certificate.
/**
* Creates an X509 version3 certificate.
*
* @param kp KeyPair that keeps the public and private keys for the new certificate.
* @param days time to live
* @param issuerBuilder IssuerDN builder
* @param subjectBuilder SubjectDN builder
* @param domain Domain of the server.
* @param signAlgoritm Signature algorithm. This can be either a name or an OID.
* @return X509 V3 Certificate
* @throws GeneralSecurityException
* @throws IOException
*/
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
PublicKey pubKey = kp.getPublic();
PrivateKey privKey = kp.getPrivate();
byte[] serno = new byte[8];
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed((new Date().getTime()));
random.nextBytes(serno);
BigInteger serial = (new java.math.BigInteger(serno)).abs();
X500Name issuerDN = issuerBuilder.build();
X500Name subjectDN = subjectBuilder.build();
// builder
JcaX509v3CertificateBuilder certBuilder = new //
JcaX509v3CertificateBuilder(//
issuerDN, //
serial, //
new Date(), //
new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
subjectDN, //
pubKey);
// add subjectAlternativeName extension
boolean critical = subjectDN.getRDNs().length == 0;
ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
// add keyIdentifiers extensions
JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
try {
// build the certificate
ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
X509CertificateHolder cert = certBuilder.build(signer);
// verify the validity
if (!cert.isValidOn(new Date())) {
throw new GeneralSecurityException("Certificate validity not valid");
}
// verify the signature (self-signed)
ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
if (!cert.isSignatureValid(verifierProvider)) {
throw new GeneralSecurityException("Certificate signature not valid");
}
return new JcaX509CertificateConverter().getCertificate(cert);
} catch (OperatorCreationException | CertException e) {
throw new GeneralSecurityException(e);
}
}
use of org.bouncycastle.asn1.ocsp.Signature in project nhin-d by DirectProject.
the class MessageSigInspector method main.
public static void main(String[] args) {
if (args.length == 0) {
//printUsage();
System.exit(-1);
}
String messgefile = null;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
// Options
if (!arg.startsWith("-")) {
System.err.println("Error: Unexpected argument [" + arg + "]\n");
//printUsage();
System.exit(-1);
} else if (arg.equalsIgnoreCase("-msgFile")) {
if (i == args.length - 1 || args[i + 1].startsWith("-")) {
System.err.println("Error: Missing message file");
System.exit(-1);
}
messgefile = args[++i];
} else if (arg.equals("-help")) {
//printUsage();
System.exit(-1);
} else {
System.err.println("Error: Unknown argument " + arg + "\n");
//printUsage();
System.exit(-1);
}
}
if (messgefile == null) {
System.err.println("Error: missing message file\n");
}
InputStream inStream = null;
try {
inStream = FileUtils.openInputStream(new File(messgefile));
MimeMessage message = new MimeMessage(null, inStream);
MimeMultipart mm = (MimeMultipart) message.getContent();
//byte[] messageBytes = EntitySerializer.Default.serializeToBytes(mm.getBodyPart(0).getContent());
//MimeBodyPart signedContent = null;
//signedContent = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
final CMSSignedData signed = new CMSSignedData(new CMSProcessableBodyPart(mm.getBodyPart(0)), mm.getBodyPart(1).getInputStream());
CertStore certs = signed.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
SignerInformationStore signers = signed.getSignerInfos();
@SuppressWarnings("unchecked") Collection<SignerInformation> c = signers.getSigners();
System.out.println("Found " + c.size() + " signers");
int cnt = 1;
for (SignerInformation signer : c) {
Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID());
if (certCollection != null && certCollection.size() > 0) {
X509Certificate cert = (X509Certificate) certCollection.iterator().next();
System.out.println("\r\nInfo for certificate " + cnt++);
System.out.println("\tSubject " + cert.getSubjectDN());
FileUtils.writeByteArrayToFile(new File("SigCert.der"), cert.getEncoded());
byte[] bytes = cert.getExtensionValue("2.5.29.15");
if (bytes != null) {
final DERObject obj = getObject(bytes);
final KeyUsage keyUsage = new KeyUsage((DERBitString) obj);
final byte[] data = keyUsage.getBytes();
final int intValue = (data.length == 1) ? data[0] & 0xff : (data[1] & 0xff) << 8 | (data[0] & 0xff);
System.out.println("\tKey Usage: " + intValue);
} else
System.out.println("\tKey Usage: NONE");
//verify and get the digests
final Attribute digAttr = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
final DERObject hashObj = digAttr.getAttrValues().getObjectAt(0).getDERObject();
final byte[] signedDigest = ((ASN1OctetString) hashObj).getOctets();
final String signedDigestHex = org.apache.commons.codec.binary.Hex.encodeHexString(signedDigest);
System.out.println("\r\nSigned Message Digest: " + signedDigestHex);
try {
signer.verify(cert, "BC");
System.out.println("Signature verified.");
} catch (CMSException e) {
System.out.println("Signature failed to verify.");
}
// should have the computed digest now
final byte[] digest = signer.getContentDigest();
final String digestHex = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
System.out.println("\r\nComputed Message Digest: " + digestHex);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(inStream);
}
}
use of org.bouncycastle.asn1.ocsp.Signature in project nhin-d by DirectProject.
the class SMIMECryptographerImpl method createAttributeTable.
/*
* Construct an attribute table. Added private function to support multiple versions of BC libraries.
*/
public static AttributeTable createAttributeTable(ASN1EncodableVector signedAttrs) {
// Support for BC 146.... has a different constructor signature from 140
AttributeTable retVal = null;
try {
/*
* 140 version first
*/
Constructor<AttributeTable> constr = AttributeTable.class.getConstructor(DEREncodableVector.class);
retVal = constr.newInstance(signedAttrs);
} catch (Throwable t) {
if (LOGGER.isDebugEnabled()) {
StringBuilder builder = new StringBuilder("bcmail-jdk15-140 AttributeTable(DERObjectIdentifier) constructor could not be loaded..");
builder.append("\r\n\tAttempt to use to bcmail-jdk15-146 DERObjectIdentifier(ASN1EncodableVector)");
LOGGER.debug(builder.toString());
}
}
if (retVal == null) {
try {
/*
* 146 version
*/
Constructor<AttributeTable> constr = AttributeTable.class.getConstructor(ASN1EncodableVector.class);
retVal = constr.newInstance(signedAttrs);
} catch (Throwable t) {
LOGGER.error("Attempt to use to bcmail-jdk15-146 DERObjectIdentifier(ASN1EncodableVector constructor failed.", t);
}
}
return retVal;
}
use of org.bouncycastle.asn1.ocsp.Signature in project XobotOS by xamarin.
the class PKCS10CertificationRequest method verify.
/**
* verify the request using the passed in public key and the provider..
*/
public boolean verify(PublicKey pubKey, String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
Signature sig;
try {
if (provider == null) {
sig = Signature.getInstance(getSignatureName(sigAlgId));
} else {
sig = Signature.getInstance(getSignatureName(sigAlgId), provider);
}
} catch (NoSuchAlgorithmException e) {
//
if (oids.get(sigAlgId.getObjectId()) != null) {
String signatureAlgorithm = (String) oids.get(sigAlgId.getObjectId());
if (provider == null) {
sig = Signature.getInstance(signatureAlgorithm);
} else {
sig = Signature.getInstance(signatureAlgorithm, provider);
}
} else {
throw e;
}
}
setSignatureParameters(sig, sigAlgId.getParameters());
sig.initVerify(pubKey);
try {
sig.update(reqInfo.getEncoded(ASN1Encodable.DER));
} catch (Exception e) {
throw new SignatureException("exception encoding TBS cert request - " + e);
}
return sig.verify(sigBits.getBytes());
}
use of org.bouncycastle.asn1.ocsp.Signature in project oxAuth by GluuFederation.
the class RSASigner method validateSignature.
@Override
public boolean validateSignature(String signingInput, String signature) throws SignatureException {
if (getSignatureAlgorithm() == null) {
throw new SignatureException("The signature algorithm is null");
}
if (rsaPublicKey == null) {
throw new SignatureException("The RSA public key is null");
}
if (signingInput == null) {
throw new SignatureException("The signing input is null");
}
String algorithm = null;
switch(getSignatureAlgorithm()) {
case RS256:
algorithm = "SHA-256";
break;
case RS384:
algorithm = "SHA-384";
break;
case RS512:
algorithm = "SHA-512";
break;
default:
throw new SignatureException("Unsupported signature algorithm");
}
ASN1InputStream aIn = null;
try {
byte[] sigBytes = Base64Util.base64urldecode(signature);
byte[] sigInBytes = signingInput.getBytes(Util.UTF8_STRING_ENCODING);
RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] decSig = cipher.doFinal(sigBytes);
aIn = new ASN1InputStream(decSig);
ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
MessageDigest hash = MessageDigest.getInstance(algorithm, "BC");
hash.update(sigInBytes);
ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
return MessageDigest.isEqual(hash.digest(), sigHash.getOctets());
} catch (IOException e) {
throw new SignatureException(e);
} catch (NoSuchAlgorithmException e) {
throw new SignatureException(e);
} catch (InvalidKeyException e) {
throw new SignatureException(e);
} catch (InvalidKeySpecException e) {
throw new SignatureException(e);
} catch (NoSuchPaddingException e) {
throw new SignatureException(e);
} catch (BadPaddingException e) {
throw new SignatureException(e);
} catch (NoSuchProviderException e) {
throw new SignatureException(e);
} catch (IllegalBlockSizeException e) {
throw new SignatureException(e);
} catch (Exception e) {
throw new SignatureException(e);
} finally {
IOUtils.closeQuietly(aIn);
}
}
Aggregations