7

我正在尝试在 Android 上使用 Bouncycastle 读取 ASN1 对象。我希望它是一个 DERSequence,在 Bouncycastle 中它是 ASN1Sequence 的一个子类,它是 ASN1Object 的一个子类。

import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
...

ASN1InputStream ais = ...;
Object o = ais.readObject();
// Eclipse's debugger now says o is a DERSequence, as expected.

DERSequence o2 = (DERSequence)o;
ASN1Sequence o3 = o2;
ASN1Object o4 = o3;
// And o4 is now exactly what I want.

ASN1Object o5 = (ASN1Object)o;
// But this throws:
///    java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence

根据答案的反馈,我构建了另一个更短的示例:

Object o = new DERSequence();
ASN1Object o1 = new DERSequence(); // This behaves fine.
ASN1Object o2 = (ASN1Object)o; // Throws ClassCastException.

是什么导致这个演员失败?

4

2 回答 2

2

Android 在这里有一个修改过的类层次结构,请参阅http://www.netmite.com/android/mydroid/1.5/dalvik/libcore/security/src/main/java/org/bouncycastle/asn1/ASN1Sequence.java中的评论 你是绝对确定您使用的版本 DERSequence 是 ASN1Object 的子类型?

例如在这里http://www.eecs.berkeley.edu/~jonah/bc/org/bouncycastle/asn1/DERSequence.html

但不是在这里http://www.androidjavadoc.com/m3-rc37a/org/bouncycastle/asn1/DERSequence.html

于 2011-04-12T11:48:34.200 回答
0

你可以尝试执行这个:

package classtest;

import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;

public class A {

    public static void main(String[] args) {
        testCast(new DERSequence());
    }

    private static void testCast(Object o) {
        DERSequence o2 = (DERSequence) o;
        ASN1Sequence o3 = o2;
        ASN1Object o4 = o3;

        ASN1Object o5 = (ASN1Object) o;
    }

}

(对我来说,这不会引发任何异常)

如果这不起作用,您应该检查 vickirk 的答案

于 2011-04-12T11:51:56.440 回答