我正在尝试在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.
导致此演员失败的原因是什么?
答案 0 :(得分: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
答案 1 :(得分: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的答案