Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
BEGIN LICENSE BLOCK ***** Version: CPL 1.0/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Common Public License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.eclipse.org/legal/cpl-v10.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2006, 2007 Ola Bini <ola@ologix.com> Alternatively, the contents of this file may be used under the terms of either of the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the CPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the CPL, the GPL or the LGPL. END LICENSE BLOCK ***
 
 package org.jruby.ext.openssl;
 
 import java.util.List;
 
 import  org.bouncycastle.asn1.ASN1EncodableVector;
 import  org.bouncycastle.asn1.ASN1Set;
 import  org.bouncycastle.asn1.DERObject;
 import  org.bouncycastle.asn1.DERObjectIdentifier;
 import  org.bouncycastle.asn1.DERSequence;
 import  org.bouncycastle.asn1.DERSet;
 import  org.bouncycastle.asn1.DERString;
 import org.jruby.Ruby;

Author(s):
Ola Bini
 
 @SuppressWarnings("deprecation")
 public class Request extends RubyObject {
     private static final long serialVersionUID = -5551557929791764918L;
 
     private static ObjectAllocator REQUEST_ALLOCATOR = new ObjectAllocator() {
         public IRubyObject allocate(Ruby runtimeRubyClass klass) {
             return new Request(runtimeklass);
         }
     };
     
     public static void createRequest(Ruby runtimeRubyModule mX509) {
         RubyClass cRequest = mX509.defineClassUnder("Request",runtime.getObject(),);
         RubyClass openSSLError = runtime.getModule("OpenSSL").getClass("OpenSSLError");
         mX509.defineClassUnder("RequestError",openSSLError,openSSLError.getAllocator());
 
         cRequest.defineAnnotatedMethods(Request.class);
     }
 
     private IRubyObject version;
     private IRubyObject subject;
     private IRubyObject public_key;
     private boolean valid = false;
 
     private List<IRubyObjectattrs;
 
 
     public Request(Ruby runtimeRubyClass type) {
         super(runtime,type);
          = new ArrayList<IRubyObject>();
     }
 
     @JRubyMethod(name="initialize", frame=true, rest=true)
     public IRubyObject _initialize(IRubyObject[] argsBlock block) {
         if(org.jruby.runtime.Arity.checkArgumentCount(getRuntime(),args,0,1) == 0) {
             return this;
         }
        byte[] req_bytes = OpenSSLImpl.readX509PEM(args[0]);
         = new PKCS10CertificationRequestExt(req_bytes);
         = getRuntime().newFixnum(.getVersion());
        String algo = null;
        byte[] enc = null;
        try {
            PublicKey pkey = (PublicKey) OpenSSLReal.getWithBCProvider(new OpenSSLReal.Callable() {
                public Object call() throws GeneralSecurityException {
                    return .getPublicKey("BC");
                }
            });
            algo = pkey.getAlgorithm();
            enc = pkey.getEncoded();
        } catch (GeneralSecurityException gse) {
            throw newX509ReqError(getRuntime(), gse.getMessage());
        }
        if("RSA".equalsIgnoreCase(algo)) {
            this. = Utils.newRubyInstance(getRuntime(), "OpenSSL::PKey::RSA", RubyString.newString(getRuntime(), enc));
        } else if("DSA".equalsIgnoreCase(algo)) {
            this. = Utils.newRubyInstance(getRuntime(), "OpenSSL::PKey::DSA", RubyString.newString(getRuntime(), enc));
        } else {
            throw getRuntime().newLoadError("not implemented algo for public key: " + algo);
        }
        org.bouncycastle.asn1.x509.X509Name subName = .getCertificationRequestInfo().getSubject();
         = Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Name");
        DERSequence subNameD = (DERSequence)subName.toASN1Object();
        for(int i=0;i<subNameD.size();i++) {
            DERSequence internal = (DERSequence)((DERSet)subNameD.getObjectAt(i)).getObjectAt(0);
            Object oid = internal.getObjectAt(0);
            Object v = null;
            if(internal.getObjectAt(1) instanceof DERString) {
                v = ((DERString)internal.getObjectAt(1)).getString();
            }
            Object t = getRuntime().newFixnum(ASN1.idForClass(internal.getObjectAt(1).getClass()));
            ((X509Name)).addEntry(oid,v,t);
        }
        // Attributes ::= SET OF Attribute
        ASN1Set in_attrs = .getCertificationRequestInfo().getAttributes();
        for(Enumeration enm = in_attrs.getObjects();enm.hasMoreElements();) {
            // Attribute ::= SEQUENCE { type, values SET SIZE(1..MAX) }
            DERSequence val = (DERSequence)enm.nextElement();
            DERObjectIdentifier v0 = (DERObjectIdentifier)val.getObjectAt(0);
            DERObject v1 = (DERObject)val.getObjectAt(1);
            IRubyObject a1 = getRuntime().newString(ASN1.getSymLookup(getRuntime()).get(v0));
            IRubyObject a2 = ASN1.decode(getRuntime().getClassFromPath("OpenSSL::ASN1"), RubyString.newString(getRuntime(), v1.getDEREncoded()));
            add_attribute(Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Attribute"new IRubyObject[] { a1a2 }));
        }
        this. = true;
        return this;
    }
    @Override
    public IRubyObject initialize_copy(IRubyObject obj) {
        ..println("WARNING: unimplemented method called: init_copy");
        if(this == obj) {
            return this;
        }
        checkFrozen();
         = getRuntime().getNil();
         = getRuntime().getNil();
         = getRuntime().getNil();
        return this;
    }
    @JRubyMethod(name={"to_pem","to_s"})
    public IRubyObject to_pem() {
        StringWriter w = new StringWriter();
        try {
            PEMInputOutput.writeX509Request(w);
            return getRuntime().newString(w.toString());
        } catch (IOException ex) {
            throw getRuntime().newIOErrorFromException(ex);
        }
        finally {
            try { w.close(); } catchException e ) {}
        }
    }
    public IRubyObject to_der() {
        return RubyString.newString(getRuntime(), .getDEREncoded());
    }
    public IRubyObject to_text() {
        ..println("WARNING: unimplemented method called: to_text");
        return getRuntime().getNil();
    }
   public IRubyObject version() {
        return this.;
    }
    @JRubyMethod(name="version=")
    public IRubyObject set_version(IRubyObject val) {
        if(val != ) {
             = false;
        }
        this. = val;
        if(!val.isNil() &&  != null) {
            .setVersion(RubyNumeric.fix2int(val));
        }
        return val;
    }
    public IRubyObject subject() {
        return this.;
    }
    @JRubyMethod(name="subject=")
    public IRubyObject set_subject(IRubyObject val) {
        if(val != ) {
             = false;
        }
        this. = val;
        return val;
    }
    public IRubyObject signature_algorithm() {
        ..println("WARNING: unimplemented method called: signature_algorithm");
        return getRuntime().getNil();
    }
    public IRubyObject public_key() {
        return this.;
    }
    @JRubyMethod(name="public_key=")
    public IRubyObject set_public_key(IRubyObject val) {
        if(val != ) {
             = false;
        }
        this. = val;
        return val;
    }
    public IRubyObject sign(final IRubyObject keyfinal IRubyObject digest) {
        final String keyAlg = ((PKey)).getAlgorithm();
        final String digAlg = ((Digest)digest).getShortAlgorithm();
        
        if(("DSA".equalsIgnoreCase(keyAlg) && "MD5".equalsIgnoreCase(digAlg)) || 
           ("RSA".equalsIgnoreCase(keyAlg) && "DSS1".equals(((Digest)digest).name().toString())) ||
           ("DSA".equalsIgnoreCase(keyAlg) && "SHA1".equals(((Digest)digest).name().toString()))) {
            throw newX509ReqError(getRuntime(), null);
        }
        final ASN1EncodableVector v1 = new ASN1EncodableVector();
        for(Iterator<IRubyObjectiter = .iterator();iter.hasNext();) {
            v1.add(((Attribute)iter.next()).toASN1());
        }
        try {
            // PKCS10CertificationRequestExt depends BC.
            OpenSSLReal.doWithBCProvider(new OpenSSLReal.Runnable() {
                public void run() throws GeneralSecurityException {
                     = new PKCS10CertificationRequestExt(digAlg + "WITH" + keyAlg,
                            ((X509Name).getRealName(),
                            ((PKey).getPublicKey(),
                            new DERSet(v1),
                            ((PKeykey).getPrivateKey(),
                            "BC");
                }
            });
        } catch (GeneralSecurityException gse) {
            throw newX509ReqError(getRuntime(), gse.getMessage());
        }
        .setVersion(RubyNumeric.fix2int());
         = true;
        return this;
    }
    public IRubyObject verify(IRubyObject key) {
        try {
            return  && .verify(((PKey)(key.callMethod(getRuntime().getCurrentContext(),"public_key"))).getPublicKey()) ? getRuntime().getTrue() : getRuntime().getFalse();
        } catch(Exception e) {
            return getRuntime().getFalse();
        }
    }
    public IRubyObject attributes() {
        return getRuntime().newArray();
    }
    @SuppressWarnings("unchecked")
    @JRubyMethod(name="attributes=")
    public IRubyObject set_attributes(IRubyObject val) {
         = false;
        .clear();
        .addAll(((RubyArray)val).getList());
        if( != null) {
            ASN1EncodableVector v1 = new ASN1EncodableVector();
            for(Iterator<IRubyObjectiter = .iterator();iter.hasNext();) {
                v1.add(((Attribute)iter.next()).toASN1());
            }
            .setAttributes(new DERSet(v1));
        }
        return val;
    }
    public IRubyObject add_attribute(IRubyObject val) {
         = false;
        .add(val);
        if( != null) {
            ASN1EncodableVector v1 = new ASN1EncodableVector();
            for(Iterator<IRubyObjectiter = .iterator();iter.hasNext();) {
                v1.add(((Attribute)iter.next()).toASN1());
            }
            .setAttributes(new DERSet(v1));
        }
        return getRuntime().getNil();
    }
    private static RaiseException newX509ReqError(Ruby runtimeString message) {
        return Utils.newError(runtime"OpenSSL::X509::RequestError"message);
    }
}// Request
New to GrepCode? Check out our FAQ X