use of com.unboundid.asn1.ASN1OctetString in project jruby-openssl by jruby.
the class PKCS7 method dataDecode.
/**
* c: PKCS7_dataDecode
*/
public BIO dataDecode(PrivateKey pkey, BIO inBio, X509AuxCertificate pcert) throws PKCS7Exception {
BIO out = null;
BIO btmp;
BIO etmp;
BIO bio;
byte[] dataBody = null;
Collection<AlgorithmIdentifier> mdSk = null;
Collection<RecipInfo> rsk = null;
AlgorithmIdentifier encAlg = null;
Cipher evpCipher = null;
RecipInfo ri = null;
int i = getType();
switch(i) {
case ASN1Registry.NID_pkcs7_signed:
dataBody = getSign().getContents().getOctetString().getOctets();
mdSk = getSign().getMdAlgs();
break;
case ASN1Registry.NID_pkcs7_signedAndEnveloped:
rsk = getSignedAndEnveloped().getRecipientInfo();
mdSk = getSignedAndEnveloped().getMdAlgs();
dataBody = getSignedAndEnveloped().getEncData().getEncData().getOctets();
encAlg = getSignedAndEnveloped().getEncData().getAlgorithm();
try {
evpCipher = EVP.getCipher(encAlg.getAlgorithm());
} catch (Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNSUPPORTED_CIPHER_TYPE, e);
}
break;
case ASN1Registry.NID_pkcs7_enveloped:
rsk = getEnveloped().getRecipientInfo();
dataBody = getEnveloped().getEncData().getEncData().getOctets();
encAlg = getEnveloped().getEncData().getAlgorithm();
try {
evpCipher = EVP.getCipher(encAlg.getAlgorithm());
} catch (Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNSUPPORTED_CIPHER_TYPE, e);
}
break;
default:
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNSUPPORTED_CONTENT_TYPE);
}
/* We will be checking the signature */
if (mdSk != null) {
for (AlgorithmIdentifier xa : mdSk) {
try {
MessageDigest evpMd = EVP.getDigest(xa.getAlgorithm());
btmp = BIO.mdFilter(evpMd);
if (out == null) {
out = btmp;
} else {
out.push(btmp);
}
} catch (Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNKNOWN_DIGEST_TYPE, e);
}
}
}
if (evpCipher != null) {
/* Find the recipientInfo which matches the passed certificate
* (if any)
*/
if (pcert != null) {
for (Iterator<RecipInfo> iter = rsk.iterator(); iter.hasNext(); ) {
ri = iter.next();
if (ri.compare(pcert)) {
break;
}
ri = null;
}
if (null == ri) {
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_NO_RECIPIENT_MATCHES_CERTIFICATE);
}
}
byte[] tmp = null;
/* If we haven't got a certificate try each ri in turn */
if (null == pcert) {
for (Iterator<RecipInfo> iter = rsk.iterator(); iter.hasNext(); ) {
ri = iter.next();
try {
tmp = EVP.decrypt(ri.getEncKey().getOctets(), pkey);
if (tmp != null) {
break;
}
} catch (Exception e) {
tmp = null;
}
ri = null;
}
if (ri == null) {
throw new PKCS7Exception(F_PKCS7_DATADECODE, R_NO_RECIPIENT_MATCHES_KEY);
}
} else {
try {
Cipher cipher = SecurityHelper.getCipher(CipherSpec.getWrappingAlgorithm(pkey.getAlgorithm()));
cipher.init(Cipher.DECRYPT_MODE, pkey);
tmp = cipher.doFinal(ri.getEncKey().getOctets());
} catch (Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATADECODE, -1, e);
}
}
ASN1Encodable params = encAlg.getParameters();
try {
String algo = org.jruby.ext.openssl.Cipher.Algorithm.getAlgorithmBase(evpCipher);
if (params != null && params instanceof ASN1OctetString) {
if (algo.startsWith("RC2")) {
// J9's IBMJCE needs this exceptional RC2 support.
// Giving IvParameterSpec throws 'Illegal parameter' on IBMJCE.
SecretKeySpec sks = new SecretKeySpec(tmp, algo);
RC2ParameterSpec s = new RC2ParameterSpec(tmp.length * 8, ((ASN1OctetString) params).getOctets());
evpCipher.init(Cipher.DECRYPT_MODE, sks, s);
} else {
SecretKeySpec sks = new SecretKeySpec(tmp, algo);
IvParameterSpec iv = new IvParameterSpec(((ASN1OctetString) params).getOctets());
evpCipher.init(Cipher.DECRYPT_MODE, sks, iv);
}
} else {
evpCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(tmp, algo));
}
} catch (Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATADECODE, -1, e);
}
etmp = BIO.cipherFilter(evpCipher);
if (out == null) {
out = etmp;
} else {
out.push(etmp);
}
}
if (isDetached() || inBio != null) {
bio = inBio;
} else {
if (dataBody != null && dataBody.length > 0) {
bio = BIO.memBuf(dataBody);
} else {
bio = BIO.mem();
}
}
out.push(bio);
return out;
}
use of com.unboundid.asn1.ASN1OctetString in project jruby-openssl by jruby.
the class PKCS7 method signatureVerify.
/* c: PKCS7_signatureVerify
*
*/
public void signatureVerify(BIO bio, SignerInfoWithPkey si, X509AuxCertificate x509) throws PKCS7Exception {
if (!isSigned() && !isSignedAndEnveloped()) {
throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, R_WRONG_PKCS7_TYPE);
}
final int md_type = ASN1Registry.oid2nid(si.getDigestAlgorithm().getAlgorithm());
BIO btmp = bio;
MessageDigest mdc = null;
for (; ; ) {
if (btmp == null || (btmp = bio.findType(BIO.TYPE_MD)) == null) {
throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, R_UNABLE_TO_FIND_MESSAGE_DIGEST);
}
mdc = ((MessageDigestBIOFilter) btmp).getMessageDigest();
if (null == mdc) {
throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, -1);
}
if (EVP.type(mdc) == md_type)
break;
btmp = btmp.next();
}
MessageDigest mdc_tmp = null;
try {
mdc_tmp = (MessageDigest) mdc.clone();
} catch (Exception e) {
}
byte[] currentData = new byte[0];
ASN1Set sk = si.getAuthenticatedAttributes();
try {
if (sk != null && sk.size() > 0) {
byte[] md_dat = mdc_tmp.digest();
ASN1OctetString message_digest = digestFromAttributes(sk);
if (message_digest == null) {
throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, R_UNABLE_TO_FIND_MESSAGE_DIGEST);
}
if (!Arrays.equals(md_dat, message_digest.getOctets())) {
throw new NotVerifiedPKCS7Exception();
}
currentData = sk.getEncoded();
}
ASN1OctetString os = si.getEncryptedDigest();
PublicKey pkey = x509.getPublicKey();
Signature sign = SecurityHelper.getSignature(EVP.signatureAlgorithm(mdc_tmp, pkey));
sign.initVerify(pkey);
if (currentData.length > 0) {
sign.update(currentData);
}
if (!sign.verify(os.getOctets())) {
throw new NotVerifiedPKCS7Exception();
}
} catch (NotVerifiedPKCS7Exception e) {
throw e;
} catch (Exception e) {
System.err.println("Other exception");
e.printStackTrace(System.err);
throw new NotVerifiedPKCS7Exception();
}
}
use of com.unboundid.asn1.ASN1OctetString in project jruby-openssl by jruby.
the class PKCS7 method dataInit.
/**
* c: PKCS7_dataInit
*/
public BIO dataInit(BIO bio) throws PKCS7Exception {
Collection<AlgorithmIdentifier> mdSk = null;
ASN1OctetString os = null;
int i = this.data.getType();
Collection<RecipInfo> rsk = null;
AlgorithmIdentifier xa = null;
CipherSpec evpCipher = null;
BIO out = null;
BIO btmp = null;
EncContent enc = null;
switch(i) {
case ASN1Registry.NID_pkcs7_signed:
mdSk = getSign().getMdAlgs();
os = getSign().getContents().getOctetString();
break;
case ASN1Registry.NID_pkcs7_signedAndEnveloped:
rsk = getSignedAndEnveloped().getRecipientInfo();
mdSk = getSignedAndEnveloped().getMdAlgs();
enc = getSignedAndEnveloped().getEncData();
evpCipher = getSignedAndEnveloped().getEncData().getCipher();
if (null == evpCipher) {
throw new PKCS7Exception(F_PKCS7_DATAINIT, R_CIPHER_NOT_INITIALIZED);
}
break;
case ASN1Registry.NID_pkcs7_enveloped:
rsk = getEnveloped().getRecipientInfo();
enc = getEnveloped().getEncData();
evpCipher = getEnveloped().getEncData().getCipher();
if (null == evpCipher) {
throw new PKCS7Exception(F_PKCS7_DATAINIT, R_CIPHER_NOT_INITIALIZED);
}
break;
case ASN1Registry.NID_pkcs7_digest:
xa = getDigest().getMd();
os = getDigest().getContents().getOctetString();
break;
default:
throw new PKCS7Exception(F_PKCS7_DATAINIT, R_UNSUPPORTED_CONTENT_TYPE);
}
if (mdSk != null) {
for (AlgorithmIdentifier ai : mdSk) {
if ((out = bioAddDigest(out, ai)) == null) {
return null;
}
}
}
if (xa != null && (out = bioAddDigest(out, xa)) == null) {
return null;
}
if (evpCipher != null) {
byte[] tmp;
btmp = BIO.cipherFilter(evpCipher.getCipher());
String algoBase = evpCipher.getCipher().getAlgorithm();
if (algoBase.indexOf('/') != -1) {
algoBase = algoBase.split("/")[0];
}
try {
KeyGenerator gen = SecurityHelper.getKeyGenerator(algoBase);
gen.init(evpCipher.getKeyLenInBits(), SecurityHelper.getSecureRandom());
SecretKey key = gen.generateKey();
evpCipher.getCipher().init(Cipher.ENCRYPT_MODE, key);
if (null != rsk) {
for (RecipInfo ri : rsk) {
PublicKey pkey = ri.getCert().getPublicKey();
Cipher cipher = SecurityHelper.getCipher(CipherSpec.getWrappingAlgorithm(pkey.getAlgorithm()));
cipher.init(Cipher.ENCRYPT_MODE, pkey);
tmp = cipher.doFinal(key.getEncoded());
ri.setEncKey(new DEROctetString(tmp));
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
throw new PKCS7Exception(F_PKCS7_DATAINIT, R_ERROR_SETTING_CIPHER, e);
}
ASN1ObjectIdentifier encAlgo = ASN1Registry.sym2oid(evpCipher.getOsslName());
if (encAlgo == null) {
throw new PKCS7Exception(F_PKCS7_DATAINIT, R_CIPHER_HAS_NO_OBJECT_IDENTIFIER);
}
if (evpCipher.getCipher().getIV() != null) {
enc.setAlgorithm(new AlgorithmIdentifier(encAlgo, new DEROctetString(evpCipher.getCipher().getIV())));
} else {
enc.setAlgorithm(new AlgorithmIdentifier(encAlgo));
}
if (out == null) {
out = btmp;
} else {
out.push(btmp);
}
}
if (bio == null) {
if (isDetached()) {
bio = BIO.nullSink();
} else if (os != null && os.getOctets().length > 0) {
bio = BIO.memBuf(os.getOctets());
}
if (bio == null) {
bio = BIO.mem();
bio.setMemEofReturn(0);
}
}
if (out != null) {
out.push(bio);
} else {
out = bio;
}
return out;
}
use of com.unboundid.asn1.ASN1OctetString in project jruby-openssl by jruby.
the class PKCS7 method dataFinal.
/**
* c: PKCS7_dataFinal
*/
public int dataFinal(BIO bio) throws PKCS7Exception {
Collection<SignerInfoWithPkey> siSk = null;
BIO btmp;
byte[] buf;
MessageDigest mdc = null;
MessageDigest ctx_tmp = null;
ASN1Set sk;
int i = this.data.getType();
switch(i) {
case ASN1Registry.NID_pkcs7_signedAndEnveloped:
siSk = getSignedAndEnveloped().getSignerInfo();
break;
case ASN1Registry.NID_pkcs7_signed:
siSk = getSign().getSignerInfo();
break;
case ASN1Registry.NID_pkcs7_digest:
break;
default:
break;
}
if (siSk != null) {
for (SignerInfoWithPkey si : siSk) {
if (si.getPkey() == null) {
continue;
}
int j = ASN1Registry.oid2nid(si.getDigestAlgorithm().getAlgorithm());
btmp = bio;
MessageDigest[] _mdc = new MessageDigest[] { mdc };
btmp = findDigest(_mdc, btmp, j);
mdc = _mdc[0];
if (btmp == null) {
return 0;
}
try {
ctx_tmp = (MessageDigest) mdc.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
sk = si.getAuthenticatedAttributes();
Signature sign = null;
try {
if (sk != null && sk.size() > 0) {
/* Add signing time if not already present */
if (null == si.getSignedAttribute(ASN1Registry.NID_pkcs9_signingTime)) {
DERUTCTime signTime = new DERUTCTime(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
si.addSignedAttribute(ASN1Registry.NID_pkcs9_signingTime, signTime);
}
byte[] md_data = ctx_tmp.digest();
ASN1OctetString digest = new DEROctetString(md_data);
si.addSignedAttribute(ASN1Registry.NID_pkcs9_messageDigest, digest);
sk = si.getAuthenticatedAttributes();
sign = SecurityHelper.getSignature(EVP.signatureAlgorithm(ctx_tmp, si.getPkey()));
sign.initSign(si.getPkey());
byte[] abuf = sk.getEncoded();
sign.update(abuf);
}
if (sign != null) {
byte[] out = sign.sign();
si.setEncryptedDigest(new DEROctetString(out));
}
} catch (Exception e) {
throw new PKCS7Exception(F_PKCS7_DATAFINAL, -1, e);
}
}
} else if (i == ASN1Registry.NID_pkcs7_digest) {
int nid = ASN1Registry.oid2nid(getDigest().getMd().getAlgorithm());
MessageDigest[] _mdc = new MessageDigest[] { mdc };
bio = findDigest(_mdc, bio, nid);
mdc = _mdc[0];
byte[] md_data = mdc.digest();
ASN1OctetString digest = new DEROctetString(md_data);
getDigest().setDigest(digest);
}
if (!isDetached()) {
btmp = bio.findType(BIO.TYPE_MEM);
if (null == btmp) {
throw new PKCS7Exception(F_PKCS7_DATAFINAL, R_UNABLE_TO_FIND_MEM_BIO);
}
buf = ((MemBIO) btmp).getMemCopy();
switch(i) {
case ASN1Registry.NID_pkcs7_signedAndEnveloped:
getSignedAndEnveloped().getEncData().setEncData(new DEROctetString(buf));
break;
case ASN1Registry.NID_pkcs7_enveloped:
getEnveloped().getEncData().setEncData(new DEROctetString(buf));
break;
case ASN1Registry.NID_pkcs7_signed:
if (getSign().getContents().isData() && getDetached() != 0) {
getSign().getContents().setData(null);
} else {
getSign().getContents().setData(new DEROctetString(buf));
}
break;
case ASN1Registry.NID_pkcs7_digest:
if (getDigest().getContents().isData() && getDetached() != 0) {
getDigest().getContents().setData(null);
} else {
getDigest().getContents().setData(new DEROctetString(buf));
}
break;
}
}
return 1;
}
use of com.unboundid.asn1.ASN1OctetString in project zm-mailbox by Zimbra.
the class UBIDLdapContext method searchPaged.
@Override
public void searchPaged(SearchLdapOptions searchOptions) throws ServiceException {
int maxResults = searchOptions.getMaxResults();
String base = searchOptions.getSearchBase();
ZLdapFilter filter = searchOptions.getFilter();
Set<String> binaryAttrs = searchOptions.getBinaryAttrs();
SearchScope searchScope = ((UBIDSearchScope) searchOptions.getSearchScope()).getNative();
SearchLdapOptions.SearchLdapVisitor visitor = searchOptions.getVisitor();
SearchGalResult searchGalResult = searchOptions.getSearchGalResult();
int pageSize = searchOptions.getResultPageSize();
int offset = 0;
boolean pagination = false;
int limit = 0;
String prevLastReturnedItemCreateDate = null;
if (searchGalResult != null) {
offset = searchGalResult.getLdapMatchCount();
prevLastReturnedItemCreateDate = searchGalResult.getLdapTimeStamp();
pagination = searchGalResult.getHadMore();
limit = searchGalResult.getLimit();
}
if (GalOp.sync == searchOptions.getGalOp() && !pagination) {
limit = 0;
}
if (limit == 0) {
limit = Integer.MAX_VALUE;
}
int pageCount = 0;
int pageOffset = 0;
int currentPage = 0;
int index = 0;
if (offset > 0) {
pageCount = offset / pageSize;
pageOffset = offset % pageSize;
}
String newToken = "";
// TODO: this is the legacy behavior, we can make it a param
boolean wantPartialResult = true;
try {
SearchRequest searchRequest = new SearchRequest(base, searchScope, derefAliasPolicy, maxResults, 0, false, ((UBIDLdapFilter) filter).getNative());
searchRequest.setAttributes(searchOptions.getReturnAttrs());
// Set the page size and initialize the cookie that we pass back in subsequent pages
ASN1OctetString cookie = null;
int count = offset;
do {
List<Control> controls = Lists.newArrayListWithCapacity(2);
if (searchOptions.isUseControl()) {
controls.add(new SimplePagedResultsControl(pageSize, cookie));
}
if (searchOptions.isManageDSAit()) {
controls.add(new ManageDsaITRequestControl(false));
}
searchRequest.setControls(controls.toArray(new Control[0]));
SearchResult result = null;
try {
result = UBIDLdapOperation.SEARCH.execute(this, searchRequest, filter);
} catch (LDAPException e) {
if (ResultCode.SIZE_LIMIT_EXCEEDED == e.getResultCode() && wantPartialResult) {
// if callsite wants partial result, return them
LDAPResult ldapResult = e.toLDAPResult();
if (ldapResult instanceof SearchResult) {
SearchResult searchResult = (SearchResult) ldapResult;
for (SearchResultEntry entry : searchResult.getSearchEntries()) {
String dn = entry.getDN();
UBIDAttributes ubidAttrs = new UBIDAttributes(entry);
if (visitor.wantAttrMapOnVisit()) {
visitor.visit(dn, ubidAttrs.getAttrs(binaryAttrs), ubidAttrs);
} else {
visitor.visit(dn, ubidAttrs);
}
newToken = ubidAttrs.getAttrString("whenCreated") != null ? ubidAttrs.getAttrString("whenCreated") : ubidAttrs.getAttrString("createTimeStamp");
}
if (searchGalResult != null) {
searchGalResult.setLdapTimeStamp(newToken);
searchGalResult.setLdapMatchCount(1);
searchGalResult.setHadMore(true);
}
}
}
// always re-throw
throw e;
}
List<SearchResultEntry> entries = result.getSearchEntries();
boolean hasMore = false;
int resultSize = entries.size();
if (resultSize > (limit + pageOffset)) {
hasMore = true;
}
String leCreateDate = null;
if (currentPage >= pageCount) {
leCreateDate = getLastEntryCreationDate(limit + pageOffset, entries);
if (prevLastReturnedItemCreateDate != null && !prevLastReturnedItemCreateDate.equals(leCreateDate)) {
count = 0;
}
for (index = pageOffset; index < entries.size() && limit > 0; index++) {
SearchResultEntry entry = entries.get(index);
String dn = entry.getDN();
UBIDAttributes ubidAttrs = new UBIDAttributes(entry);
if (visitor.wantAttrMapOnVisit()) {
visitor.visit(dn, ubidAttrs.getAttrs(binaryAttrs), ubidAttrs);
} else {
visitor.visit(dn, ubidAttrs);
}
limit--;
newToken = ubidAttrs.getAttrString("whenCreated") != null ? ubidAttrs.getAttrString("whenCreated") : ubidAttrs.getAttrString("createTimeStamp");
if (newToken != null && newToken.equals(leCreateDate)) {
count++;
}
}
prevLastReturnedItemCreateDate = leCreateDate;
pageOffset = 0;
}
cookie = null;
for (Control c : result.getResponseControls()) {
if (c instanceof SimplePagedResultsControl) {
cookie = ((SimplePagedResultsControl) c).getCookie();
}
}
if (searchGalResult != null && (GalOp.sync == searchOptions.getGalOp())) {
if (limit == 0 && (((cookie != null) && (cookie.getValueLength() > 0)) || hasMore)) {
searchGalResult.setHadMore(true);
searchGalResult.setLdapTimeStamp(newToken);
searchGalResult.setLdapMatchCount(count);
} else if (((cookie != null) && (cookie.getValueLength() == 0))) {
searchGalResult.setHadMore(false);
searchGalResult.setLdapMatchCount(0);
}
}
currentPage++;
} while ((cookie != null) && (cookie.getValueLength() > 0) && limit > 0);
} catch (SearchLdapOptions.StopIteratingException e) {
// break out of the loop and close the ne
} catch (LDAPException e) {
throw mapToLdapException("unable to search ldap", e);
}
}
Aggregations